使用ASP.Net MVC上传文件 - 获取名称但没有文件流,我做错了什么?

Jas*_*ler 41 asp.net-mvc upload

我认为这个表格有:

<!-- Bug (extra 'i') right here-----------v  -->
<!-- was: <form method="post" enctype="mulitipart/form-data" action="/Task/SaveFile"> -->
<form method="post" enctype="multipart/form-data" action="/Task/SaveFile">
<input type="file" id="FileBlob" name="FileBlob"/>
<input type="submit"  value="Save"/>
<input type="button" value="Cancel" onclick="window.location.href='/'" />
</form>
Run Code Online (Sandbox Code Playgroud)

这个代码在我的控制器中:

public ActionResult SaveFile( FormCollection forms )
{
   bool errors = false;
   //this field is never empty, it contains the selected filename
   if ( string.IsNullOrEmpty( forms["FileBlob"] ) )
   {
       errors = true;
       ModelState.AddModelError( "FileBlob", "Please upload a file" );
   }
   else
   {
      string sFileName = forms["FileBlob"];
      var file = Request.Files["FileBlob"];
      //'file' is always null, and Request.Files.Count is always 0 ???
      if ( file != null )
      {
         byte[] buf = new byte[file.ContentLength];
         file.InputStream.Read( buf, 0, file.ContentLength );
         //do stuff with the bytes
      }
      else
      {
         errors = true;
         ModelState.AddModelError( "FileBlob", "Please upload a file" );
      }
   }
   if ( errors )
   {
      return ShowTheFormAgainResult(); 
   }
   else
   {
      return View();
   }
}
Run Code Online (Sandbox Code Playgroud)

基于我能够找到的每个代码示例,这似乎是这样做的方式.我尝试过小文件和大文件,结果没有区别.表单字段始终包含与我选择的文件名匹配的文件名,并且Request.Files集合始终为空.

我不认为这是相关的,但我正在使用VS Development Web Server.AFAIK它支持与IIS相同的文件上传.

现在已经很晚了,我有可能错过一些明显的东西.我很感激任何建议.

Jas*_*ler 51

我不知道发布亵渎政策的政策是什么,但问题在于:

enctype="mulitipart/form-data"
Run Code Online (Sandbox Code Playgroud)

额外i的内容阻止了文件上传.不得不运行Fiddler,看它从来没有发送过该文件.

它应该是:

enctype="multipart/form-data"
Run Code Online (Sandbox Code Playgroud)

  • 由于从这篇文章中复制粘贴了enctype,我已经有两次这个问题了! (2认同)

Jas*_*son 16

对于未来可能偶然发现这篇文章的人来说,这是Scott Hanselman关于这个主题的一篇精彩文章:回归基础案例研究:使用ASP.NET MVC实现HTTP文件上传,包括测试和模拟

  • Phil Haack的更新版本,包括ASP.Net MVC2的增强功能:http://haacked.com/archive/2010/07/16/uploading-files-with-aspnetmvc.aspx (10认同)