MVC 文件上传问题

在用MVC作文件上传处理时,最开始是这样的。

html代码

 <div id="dialog" title="Upload files">       
    <% using (Html.BeginForm("UploadFile", "UploadFile", FormMethod.Post))
    {%><br />
        <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> ;</p><br />
        <p><input type="submit" value="Upload file" /></p>       
    <% } %>   
</div>

控制器中代码为:

   public ActionResult UploadFile()
        {
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult UploadFile(FormCollection collection)
        {
            foreach (string inputTagName in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[inputTagName];
                if (file.ContentLength > 0)
                {
                    string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads")
                    , Path.GetFileName(file.FileName));
                    file.SaveAs(filePath);
                }
            }
            return View();
        }
    }

可是怎么也上传不了文件。跟踪到foreach (string inputTagName in Request.Files)这句时,发现当中的Request.Files中包含的文件数量为0,也就是说要上传的文件没有没上来。

检查了很长时间也没有发现是什么问题。

最后,发现要把HTML代码中的using语句加上, new { enctype = "multipart/form-data" },改成这样:

<% using (Html.BeginForm("UploadFile", "UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))

就把问题解决了。

这是什么原因呢?

原来,

ENCTYPE="multipart/form-data"用于表单里有图片上传。

表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作.
enctype="multipart/form-data"是上传二进制数据; form里面的input的值以2进制的方式传过去。
form里面的input的值以2进制的方式传过去,所以request就得不到值了。 也就是说加了这段代码,用request就会传递不成功。

1、指定表单提交方式和路径等

 @using (Html.BeginForm("Index", "Home", FormMethod.Get, new { name = "nbform", id = "nbform" }))

2、指定表单提交为数据方式

 @using (Html.BeginForm("ImportExcel", "Stock", FormMethod.Post, new { enctype = "multipart/form-data" }))

 注意, 有时候要加{id=1}不然在点击超过第一页的索引时form后面会自动加上当前页的索引,如果此时再搜索则可能会出来“超出索引值”的错误提示
       @using (Html.BeginForm("Index", null, new { id = 1 }, FormMethod.Get))

3、下面的操作可以防止提交链接后面自带参数

@using (Html.BeginForm("AddDIYBillOfLading", "BillOfLading", new { id ="" }, FormMethod.Post, new { name = "myform", id = "myform" }))

即,RouteValues的id=""

原文地址:https://www.cnblogs.com/eric-qin/p/5694117.html