2011-12-18 61 views
37

我在ASP.NET MVC中上传文件时遇到问题。 我的代码如下:HttpPostedFileBase总是在ASP.NET MVC中返回空值

查看:

@{ 
    ViewBag.Title = "Index"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>Index2</h2> 
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" /> 
    <input type="submit" /> 
} 

控制器:

[HttpPost] 
public ActionResult FileUpload(HttpPostedFileBase uploadFile) 
{ 
    if (uploadFile != null && uploadFile.ContentLength > 0) 
    { 
     string filePath = Path.Combine(Server.MapPath("/Temp"), Path.GetFileName(uploadFile.FileName)); 
     uploadFile.SaveAs(filePath); 
    } 
    return View(); 
} 

但uploadFile总是返回null。 任何人都可以找出原因吗?

回答

94
@{ 
    ViewBag.Title = "Index"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 
} 

<h2>Index2</h2> 
@using (Html.BeginForm("FileUpload", "Board", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 
    <input type="file" name="uploadFile"/> 
    <input type="submit" /> 
} 

你必须提供名称输入类型的文件,以uploadFile为了在ASP.net MVC模型绑定工作,
也确保的HttpPostedFileBase您输入的文件类型和参数名的名是相同的。

+0

哇......非常感谢。我不知道这个MVC。我对ASP.NET MVC很陌生。谢谢。 – 2011-12-18 13:29:27

+36

我没有错过字段名称,但由于缺少表单定义中的enctype参数而出现相同的'空'问题。感谢这个例子。 – niallsco 2012-04-02 08:54:17

+0

@dotnetstep谢谢 – anpatel 2012-11-29 15:31:38

0

还有另一种情况。在我的情况下,我得到这个问题,因为我直接在我的MVC视图中呈现脚本标记,并且IE在那里给出问题。

鉴于

正确的代码应该如下:

@section scripts 
{ 
    <script> 
     $(document).ready(function() { 
      $('.fileinput').fileinput(); 
... 
} 
6

我试过最网上发布这个主题的解决方案,但发现它更好地使用一种解决方法,而不是..

这真的并不重要,我所做的HttpPostedFileBase和/或HttpPostedFile始终为空。使用HttpContext.Request.Files集合似乎没有任何麻烦。

例如

if (HttpContext.Request.Files.AllKeys.Any()) 
     { 
      // Get the uploaded image from the Files collection 
      var httpPostedFile = HttpContext.Request.Files[0]; 

      if (httpPostedFile != null) 
      { 
       // Validate the uploaded image(optional) 

       // Get the complete file path 
       var fileSavePath =(HttpContext.Server.MapPath("~/UploadedFiles") + httpPostedFile.FileName.Substring(httpPostedFile.FileName.LastIndexOf(@"\"))); 

       // Save the uploaded file to "UploadedFiles" folder 
       httpPostedFile.SaveAs(fileSavePath); 
      } 
     } 

在上面的例子中,我只抢到的第一个文件,但它仅仅是一个循环,虽然收集保存所有文件的问题。

HTH

罗布

3

我的方案的问题是与id属性,我有这样的:

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

的soultion是消除ID:

​​
+3

Damm,在我的情况下,我使用HttpPostedFile而不是HttpPostedFileBase ..程序员错误:/ – 2015-10-21 16:13:19

+0

塞缪尔你救了我的一天!虽然它在http://stackoverflow.com/a/24911221/2346618解释我认为在签名中使用基类HttpPostedFileBase是愚蠢的。在面向对象编程中,基类用于帮助构造具体类和接口用于协议。使用像IHttpPostedFile这样的接口将不太容易出错。 – 2016-01-31 17:36:41