【问题标题】:Image upload MVC5图片上传MVC5
【发布时间】:2016-03-04 17:19:20
【问题描述】:

我需要上传一张图片并将其保存到一个文件中,但我无法在控制器中捕获它,因为它始终为空。

在视图中:

@using(Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = "multipart/form-data "}))
{
    ....
    <input type="file" name="file" id="file" />

控制器:

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ProductID,FKSubCategoryID,ProductEnName,ProductArName,ProductEnDescription,ProductArDescription,ProductImage")] Product product,HttpPostedFileBase file)
{ 
    if (ModelState.IsValid)
    {
        product.FKBrandID = 1;
        db.Products.Add(product);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(product);
}

我已经试过了:

  • 使用 HttpPostedFileBase 代替 HttpPostedFile
  • Request.Files["file"]null
  • 输入中的参数名称与ActionResult相同
  • enctype = "multipart/form-data ", data_ajax = "false"
  • 添加[AcceptVerbs(HttpVerbs.Post)]

这让我发疯了,请大家给点建议?

【问题讨论】:

  • 你如何提交这个(标准提交或 ajax)?
  • 使用标准提交
  • 那么data_ajax = "false"是什么?哪个建议ajax? - 如果你有 @usng (Html.BeginForm(......, new { enctype = "multipart/form-data" })) 它应该可以正常工作
  • 我尝试了使用和不使用 data_ajax = "false" 以防万一。我有 (Html.BeginForm("Create", "Products", FormMethod.Post, new { enctype = " multipart/form-data "})) 仍然没有文件
  • 您在name="file" 的视图中还有其他输入吗?

标签: file-upload asp.net-mvc-5


【解决方案1】:

问题是,您为enctype 属性提供的值无效!

仔细看看。在关闭双引号之前有一个空格!

new { enctype = "multipart/form-data "}

应该是new { enctype = "multipart/form-data"}

下面的代码应该可以正常工作。

@using(Html.BeginForm("Create", "Products", FormMethod.Post,
                                                 new { enctype = "multipart/form-data"}))
{  
   <input type="file" name="file" id="file"/>
   <input type="submit"/>

}

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 2021-03-19
    • 2010-12-02
    • 2010-12-15
    • 1970-01-01
    • 2018-03-22
    相关资源
    最近更新 更多