使用 ASP.Net MVC 上传文件 - 获取名称但没有文件流,我做错了什么? [英] Uploading Files with ASP.Net MVC - get name but no file stream, what am I doing wrong?

查看:8
本文介绍了使用 ASP.Net MVC 上传文件 - 获取名称但没有文件流,我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为有这个表格:

<!-- 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>

我的控制器中的这段代码:

And this code in my controller:

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();
   }
}

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

Based on every code sample I've been able to find, this seems like the way to do it. I've tried with small and large files, with no difference in the result. The form field always contains the filename which matches what I've chosen, and the Request.Files collection is always empty.

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

I don't think it's relevant, but I'm using the VS Development Web Server. AFAIK it supports file uploads the same as IIS.

时间不早了,我可能会遗漏一些明显的东西.我会很感激任何建议.

It's getting late and there's a chance I'm missing something obvious. I'd be grateful for any advice.

推荐答案

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

I don't know what the policy is on posting profanity, but here's the problem:

enctype="mulitipart/form-data"

其中额外的 i 阻止了文件上传.必须运行 Fiddler 才能看到它从一开始就没有发送文件.

The extra i in there stopped the file from uploading. Had to run Fiddler to see that it was never sending the file in the first place.

应该是:

enctype="multipart/form-data"

这篇关于使用 ASP.Net MVC 上传文件 - 获取名称但没有文件流,我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆