tags:

views:

153

answers:

2

Hi,

I have googled this code to upload a file with MVC.

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

But when interrogate the forms["FileBlob"] it is null when I browse a file and submit the form????

Malcolm

EDIT: I have added a textbox to the form and I can get that value fine. Just the input type file is not working?

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();
   }
}
+1  A: 

Woah that is one confusing setup, I personally would never complicate things like that with all those if statements and for null values do via jquery validation you can also do server side validation. Instead of checking if(errors) do if(ModelState.IsValid){ return View();} here is a better interpretation

http://msdn.microsoft.com/en-us/library/dd410404.aspx

this way you can get rid of that bool setup.

Also check here

http://blogs.msdn.com/stcheng/archive/2009/03/20/asp-net-how-to-implement-file-upload-and-download-in-asp-net-mvc.aspx

for an easier implemenation of your upload structure. I've used it and didn't run into any problems.

Ayo
A: 

This answer might help. Also, i'd suggest not posting other form fields with the uploading file.. do that separately in a separate action. Sure this gives the user 2 steps, but believe me it's worth the simplicity on your end.

cottsak