加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 00:06:33 所属栏目:百科 来源:网络整理
导读:嗨我发布图片时似乎遇到了问题.我已经在stackoverflow和其他讨论这个主题的论坛上检查了很多问题,但似乎没有提供我需要的答案.这是我的代码: @using( Html.BeginForm("Create","ProductManager",FormMethod.Post,new{enctype = "multipart/form-data"})){ u
嗨我发布图片时似乎遇到了问题.我已经在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,似乎它甚至没有发布

我怎样才能解决这个问题呢?

解决方法

您必须使用将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属性是浏览器在提交时在发布/获取表单上发送的内容.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读