简体   繁体   English

HttpPostedFileBase始终返回null,并且不会发布图像

[英]HttpPostedFileBase always returns null and image does not get posted

Hi I seem to be having a problem when posting images.I have checked many questions on stackoverflow and on other forums that discuss this topic but none seem to provide the answer I need.Here is my code: 嗨我发布图片时似乎遇到了问题。我已经在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;
        }

From debugging I found that HttpPostedFileBase returns null.The other form data in the collection gets posted succesfully.Only the image does not get posted.I can not seem to acces ProductAvatar from either the FormCollection or the HttpPostedFileBase , it seems like it's not even posted 从调试我发现HttpPostedFileBase返回null。集合中的其他表单数据成功发布。只有图像没有发布。我似乎无法从FormCollection或HttpPostedFileBase访问ProductAvatar,似乎它甚至没有发布

How can I corect this problem? 我怎样才能解决这个问题呢?

You have to use change the name of your HttpPostedFile parameter to the same name of your input file on the form, or you also can use Request.Files and get by the by the name attribute of your input file, try something like this: 您必须使用将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");
}

The name attribute is what the browser will send on a post/get form when submit. name属性是浏览器在提交时在发布/获取表单上发送的内容。

Your action method parameter name needs to match the file input name. 您的操作方法参数名称需要与文件输入名称匹配。

So with this: 所以这个:

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

You'll need a method signature like: 你需要一个方法签名,如:

public ActionResult Create(FormCollection collection, HttpPostedFileBase productAvatar)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM