Uploading files using ASP.Net MVC - get a name but no file stream, what am I doing wrong?

I have this form in my opinion:

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

Based on each sample code I could find, this seems like a way to do this. I tried with small and large files, without any difference in the result. The form field always contains the file name that matches my choice, and the Request.Files collection is always empty.

I do not think this is relevant, but I am using VS Development Web Server. AFAIK supports downloading files in the same way as IIS.

It is getting late, and there is a chance that I will miss something obvious. I would appreciate any advice.

+41
upload asp.net-mvc
Nov 18 '08 at 5:53
source share
4 answers

I don’t know what a policy is when publishing profanity, but here is the problem:

 enctype="mulitipart/form-data" 

Additional i there stopped downloading the file. I had to run Fiddler to see that it never sent the file in the first place.

He should read:

 enctype="multipart/form-data" 
+50
Nov 18 '08 at 6:38
source share

For people who might stumble upon this post in the future, here is Scott Hanselman’s excellent post on the topic: Back to the basics Case Study: Implementing Uploading an HTTP File Using ASP.NET MVC, Including Tests and Layouts .

+16
Dec 10 '09 at 19:58
source share
 var file = Request.Files[sFileName]; 

it should be...

 var file = Request.Files["FileBlob"]; 

which said Request.Files.Count should be 1 ... hmmm

+2
Nov 18 '08 at 5:58
source share

Good thing you found your mistake.

As a side note, you'll need a try / catch for the file processing code so that you know when file permissions, etc. not configured correctly.

0
Nov 18 '08 at 16:27
source share



All Articles