HttpPostedFileBase总是返回null和图像不被张贴

本文关键字:图像 张贴 null 返回 HttpPostedFileBase | 更新日期: 2023-09-27 17:51:06

你好,我似乎在发布图像时遇到了问题。我在stackoverflow和其他讨论这个主题的论坛上检查了许多问题,但似乎没有提供我需要的答案。下面是我的代码:

@using( Html.BeginForm("Create", "ProductManager", FormMethod.Post, new{enctype = "multipart/form-data"})){
    <ul>
        ....
        <li>
             @Html.LabelFor(model => model.ProductImagePath , "Avatar")
             <input type="file" id="ProductAvatar" name="ProductAvatar" />
             @Html.HiddenFor(model => model.ProductImagePath , new { id = "AvatarHiddenField"})
        </li>
         <li>
             @Html.LabelFor(model => model.ProductName , "Product Name")
             @Html.EditorFor(model => model.ProductName)
         </li>
         .....
    </ul>
}
[HttpPost]
        public ActionResult Create( FormCollection collection ,  HttpPostedFileBase avatar)
        {
            string file = collection["ProductAvatar"];
            var avatars = avatar;
        }

从调试我发现HttpPostedFileBase返回null。集合中的其他表单数据被成功发布。只有图片没有被发布。我似乎无法从FormCollection或HttpPostedFileBase访问ProductAvatar,似乎它甚至没有发布

如何纠正这个问题?

HttpPostedFileBase总是返回null和图像不被张贴

您必须使用更改您的HttpPostedFile参数的名称为您的输入文件的名称相同的形式,或者您也可以使用Request.Files,并通过您的输入文件的name属性,尝试这样做:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
   HttpPostedFileBase file = Request.Files["ProductAvatar"];
   if (file.ContentLength > 0)
   {
      file.SaveAs(/* path */);
   }
   // othyer tasks
   return RedirectToAction("Index");
}

name属性是浏览器在提交post/get表单时发送的内容。

您的操作方法参数名称需要与文件输入名称匹配。

所以用这个:

<input type="file" id="ProductAvatar" name="ProductAvatar" />

你需要一个这样的方法签名:

public ActionResult Create(FormCollection collection, HttpPostedFileBase productAvatar)