Uploading a File (Or Files) With ASP.NET MVC

I wanted to confirm something about how to upload a file or set of files with ASP.NET MVC and the first search result for the phrase “uploading a file with asp.net mvc” is Scott Hanselman’s blog post on the topic.

His blog post is very thorough and helps provide a great understanding of what’s happening under the hood. The only complaint I have is that the code could be much simpler since we’ve made improvements to the ASP.NET MVC 2. I write this blog post in the quixotic hopes of knocking his post from the #1 spot.

Uploading a single file

Let’s start with the view. Here’s a form that will post back to the current action.

<form action="" method="post" enctype="multipart/form-data">
  
  <label for="file">Filename:</label>
  <input type="file" name="file" id="file" />

  <input type="submit" />
</form>

Here’s the action method that this view will post to which saves the file into a directory in the App_Data folder named “uploads”.

[HttpPost]
public ActionResult Index(HttpPostedFileBase file) {
            
  if (file.ContentLength > 0) {
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
    file.SaveAs(path);
  }
            
  return RedirectToAction("Index");
}

Notice that the argument to the action method is an instance of HttpPostedFileBase. ASP.NET MVC 2 introduces a new value providers feature which I’ve covered before.

Whereas model binders are used to bind incoming data to an object model, value providers provide an abstraction for the incoming data itself.

In this case, there’s a default value provider called the HttpFileCollectionValueProvider which supplies the uploaded files to the model binder.Also notice that the argument name, file, is the same name as the name of the file input. This is important for the model binder to match up the uploaded file to the action method argument.

Uploading multiple files

In this scenario, we want to upload a set of files. We can simply have multiple file inputs all with the same name.

<form action="" method="post" enctype="multipart/form-data">
    
  <label for="file1">Filename:</label>
  <input type="file" name="files" id="file1" />
  
  <label for="file2">Filename:</label>
  <input type="file" name="files" id="file2" />

  <input type="submit"  />
</form>

Now, we just tweak our controller action to accept an IEnumerable of HttpPostedFileBase instances. Once again, notice that the argument name matches the name of the file inputs.

[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
  foreach (var file in files) {
    if (file.ContentLength > 0) {
      var fileName = Path.GetFileName(file.FileName);
      var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
      file.SaveAs(path);
    }
  }
  return RedirectToAction("Index");
}

Yes, it’s that easy. :)

What others have said

Requesting Gravatar... Andrei Rinea Jul 16, 2010 8:24 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Two small comments :

1. I wouldn't say "an enumeration of HttpPostedFileBase" but "an IEnumerable of HttpPostedFileBase" to avoid confusion with the enum type

2. If the two files come from different client folders AND have the same file name the last file will win on the server (i.e.: it will overwrite the first)
Requesting Gravatar... Brian Jul 17, 2010 3:31 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Awesome, thanks!

Perhaps you (or somebody else) has an answer to this problem. In IIS6 it seems that if you recycle the app pool any uploads occurring at the time will fail. Is this a known problem? Is there a known work-around? Is this fixed in IIS7 (it seems like it is, but I haven't fully tested it yet)?
Requesting Gravatar... haacked Jul 17, 2010 4:15 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
@andrei, thanks for the feedback. :)
Requesting Gravatar... Fynn Jul 18, 2010 11:13 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Excellent stuff. As a newbie to web development, I would like to see how best to implement the file(s) upload scenario in asp.net mvc 2 where the client is Windows application and not a web form.

Thanks.
Requesting Gravatar... Kevin Major Jul 18, 2010 11:20 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Quick question: what if you want another controller method to handle the upload? What would one have to specify as the path for the form's action attribute? Simply '/controller/method'?
Requesting Gravatar... Mike Henry Jul 18, 2010 11:48 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Nice, I was wondering how best to handle multiple files with MVC.

What is your preferred way to handle uploads that are too large (which cause System.Web.HttpException: Maximum request length exceeded)?

Thanks
Requesting Gravatar... g Jul 18, 2010 11:56 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
This works, but unless the files are small, it will only frustrate the user.

I still consider SWFUpload the gold standard. Anytime you're uploading files, you need to communicate to the UI that something is happening. The only way to do that is with Flash unfortunately (HTML5 solves this, however).
Requesting Gravatar... Nick K Jul 19, 2010 1:19 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi Phil,

Just want to point out that you should be careful with this code, because unless you have some special routing rules in place, you've just introduced a vulnerability! :(

Say I upload a file called haacked.aspx, then I can just browse to <site>/uploads/haacked.aspx and execute whatever c# code I want on your server.

You should probably either:
a) make a note of this in your post so that it doesn't bite people who use this code
b) move the upload path outside of the webroot or
c) include some fancy routing rule to stop this

Cheers :)
Requesting Gravatar... M Jul 19, 2010 2:36 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Thank you for keeping "simple" your focus. We all appreciate it!
Requesting Gravatar... Jordan Jul 19, 2010 2:37 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Fine and all, but who uploads files with postback these days? More useful if the uploads were being done with jQuery/ajax and result handled with json.
Requesting Gravatar... Phil Jul 19, 2010 3:19 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Thanks for the post. It is nice and simple.
Requesting Gravatar... Arun Mahendrakar Jul 19, 2010 1:31 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Andrei Rinea, the answer to your second question is 'yes'. It does overwrite the first one.

Arun
Requesting Gravatar... bennyb Jul 21, 2010 3:10 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi Phil,
What if I wanted to add a few textboxes such as for a freindly file name and short description, are we still going to receive the HttpPostedFileBase?
Requesting Gravatar... Tim Hobbs Jul 21, 2010 10:30 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
@Nick K-

I am pretty sure that App_Data is a "reserved" folder and won't allow any execution of code or anything. I think that is one of the ideas with those folders (App_Code, Bin, etc.): IIS knows better than to allow outside access to the contents.
Requesting Gravatar... haacked Jul 22, 2010 12:49 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
@Tim You are correct. But in fairness to Nick, I made that change to the sample after Nick suggested it. :)
Requesting Gravatar... Imranhussein Jul 23, 2010 12:31 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
@Nick, @haacked
we can validate the file and allow only to upload allowed file ext. Isn't it?
Requesting Gravatar... Morin Jul 25, 2010 8:07 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
NOT RELATED TO THIS ARTICLE:
I have a question and not able to get it answered.

stackoverflow.com/...

I would highly appreciate if anybody can answer this.

Requesting Gravatar... bennyb Jul 26, 2010 5:02 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
So how do you access other form fields e.g. TextBox, TextArea etc. added to this form?
Clearly they are not part of the HttpPostedFileBase.
Requesting Gravatar... Rony Jul 27, 2010 2:40 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi Phil,

I came across an interesting situation in one of my previous projects, HttpPostedFileBase file was NULL only in production and finally came to know that it was because of the IIS7 URL rewrite rules, is there any way you recommend to avoid that?
Requesting Gravatar... Chirag Nirmal Jul 27, 2010 6:12 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Wow.. I never thought it would be so easy. This is even simpler than asp.net file uploader control.
Requesting Gravatar... Romero Brito Jul 29, 2010 8:12 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Any ideas about how to get "asynchronous upload progress report" using this technique (for large file uploads)?
Requesting Gravatar... Joshua Hayes Jul 29, 2010 9:34 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Just did a quick google. Nope, second to Hansleman :p

I like this comment by 'Chirag'

"Wow.. I never thought it would be so easy. This is even simpler than asp.net file uploader control."

So true. ASP.NET MVC is Win!
Requesting Gravatar... Joshua Hayes Jul 29, 2010 9:37 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hey Phil,

Love your blog. I read it all the time. It's a bit old school though isn't it? I think you need to make a new one using MVC ;)
Requesting Gravatar... Thanigainathan Jul 29, 2010 3:37 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi,

Article is very nice.
Will this work all the file types. What happens if upload a exe extension.

Thanks,
Thani
Requesting Gravatar... duffy Aug 03, 2010 3:05 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
What if the user only uploads only the second file but leaves the first input field blank. Is there a way to access the id to figure which of the two files arrived at the server?
Requesting Gravatar... rakesh Sep 02, 2010 7:24 PM
# how i upload new site
please tell me how upload my new site (i don't know how upload side)if you have any site uploading please send me url

thank you
Requesting Gravatar... Eric Dorothy Sep 28, 2010 1:50 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hey Phil,

When I followed your example, I found that it uploaded several files without error, however when I attempted to upload an executable file as Thani suggested earlier I got an error. I can't even break into the controller code to find out what the problem is. If I can't upload EXE files, what other file extensions are not allowed?
Can you please shed some light on this subject?
Requesting Gravatar... Eric Dorothy Sep 28, 2010 4:51 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Sorry I am able to upload EXE files but they must be really small. If I wanted to upload an executable of any size (6 megs was my test file) then it fails.
Requesting Gravatar... Berin Loritsch Oct 06, 2010 8:55 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
To answer the questions about forms with mixed data (files and text fields), I believe I have the answer:

bloritsch.d-haven.net/...

Basically, you can use a any model you choose. As long as there is an HttpPostedFile property that matches your file upload control you are all set. Validations will even work (i.e. you can make the file upload a required field). It's pretty snazzy.

Just a note: it appears that HttpPostedFile only uses the last part of the file path to identify itself. The raw HTTP request has the full path of the client's file while Asp.Net only sees fit to give you the last part. I'm uncertain if my Model approach solves the problem of two files with the same name and different directories. I haven't tested that. It does make it easy to have some of the file upload fields required and others not.
Requesting Gravatar... Joemarie Amparo Oct 06, 2010 1:50 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hello. I've tried this but it doesnt work. I mean it does not upload anything to the uploads folder. I'm really new to programming.

What I really wanted is to upload a .csv / .xls file and display its content and at the same time export it to another excel file.

please help.

my email address is joemarieamparo@yahoo.com

thanks.
Requesting Gravatar... snatty Nov 15, 2010 11:25 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Thank a lot for code.It's do work. Thank you
Requesting Gravatar... Jerry Dec 27, 2010 3:35 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hello ...

I am Taiwan boy .

my name is Jerry.

thank you !

no books to learn ASP.NET MVC.

nice article !! thx...
Requesting Gravatar... Phil Jan 04, 2011 1:45 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hello Phil Haack,

Would just like to give you a big thanks for making these short tutorials and also always having a link to Scott Hanselman's posts because you really complement each other on information.

You've helped me a lot understanding MVC in this past week :)
Requesting Gravatar... JT Feb 02, 2011 4:23 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
If I need to make a validation that this picture has the following format gif, jpeg, png. How should I do it?

Another question is: validation the pictures width and height?

// JT
Requesting Gravatar... ChinaBoy May 02, 2011 5:50 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Nice to good site? it helped to me. Thanks. Please, can you show me the table of images in database structure and how you validate it and repopulate.
Requesting Gravatar... supreet May 20, 2011 6:02 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
thanks for the code.It rly works.
Requesting Gravatar... Shailen Jun 08, 2011 10:28 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi Scott,

I am newby to MVC. This is nice article, but can we make something like this:

http://aquantum-demo.appspot.com/file-upload

to upload multiple files, instead of providing multiple file upload controls on the page, can we select multiple files at same time?

I appreciate your help.

Requesting Gravatar... Ben Jun 12, 2011 10:00 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
I found this article through Google, and the question was asked but never answered in the comments, so I thought I would answer it.

To upload a file with other input fields you just need to provide the parameters for the Action.

[HttpPost]
public ActionResult Index(FormCollection form, HttpPostedFileBase file) {
Requesting Gravatar... arun Jul 04, 2011 11:06 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
hi this is working for me.thanks a lot.but what should be done to validate the file types withou a model
Requesting Gravatar... Manoj Aug 25, 2011 4:39 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
I Have to Upload multiple images in Sql database and retrive it to display to view page.


please help me
Thanks in advance
Requesting Gravatar... Abhay Dubey Sep 04, 2011 2:39 PM
# Can I save Two same name images on a same folder by uploading ???
Can I save Two same name images on a same folder by uploading images from different users?????????
Requesting Gravatar... Srikanth Sep 14, 2011 10:15 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi,
I need code for binding the upload files to view and downloading that files.
Requesting Gravatar... Muhammad Arif Oct 13, 2011 7:56 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
That is nice way. Good!
Requesting Gravatar... prashant Nov 04, 2011 10:03 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
nice..............
Requesting Gravatar... Themhs Nov 22, 2011 1:13 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
well the thing is that i can upload small files but when i try to upload a file 13.098 kb it crashes the system. How can i increase the size?
Requesting Gravatar... Vinca Dec 02, 2011 7:11 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Seems easy enough, but I'm getting an error on the 'Path' - "Path does not exist in current context".
I've a context file, but this is for a different page. Help?

By the way, @Themhs: you'll need to add some code in your web config page: <httpRuntime maxRequestLength="x" /> "x" being the number of KB's. I think the default is 4MB.
Requesting Gravatar... Rajesh Dec 21, 2011 11:57 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
small files upload is okay

when i upload large files it's not working.

Requesting Gravatar... Edwin Dec 28, 2011 2:20 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi, thanks for your nice article, I have a question:

Someone knows how to view what file was posted by one determinated input control file?

thanks in advance.
Requesting Gravatar... Zeesahn Umar Jan 12, 2012 1:52 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Really nice and simple tutorial
Requesting Gravatar... nice article.. Jan 15, 2012 5:50 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
It's very helpful to upload multiple images in mvc...
Requesting Gravatar... aman Jan 19, 2012 5:59 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
i hav a problem .
how to design app_data/uploads where the file will b stored
Requesting Gravatar... Hashcoderz Feb 17, 2012 12:01 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
If the selected file name contains '&#', the upload will fail. Do we have any workaround for this.
Requesting Gravatar... anonymous Feb 18, 2012 4:22 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Everyone having a problem with loading file size, please look up the maxRequestLength setting for httpRuntime in system.web (web.config). By default you are limited to 4 MB.
Requesting Gravatar... Anonymous Mar 29, 2012 7:12 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Great post! Thanks. And yes it's now #1 on google!
Requesting Gravatar... Ahsan Apr 10, 2012 9:20 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Guys , i need to upload images using ajax in mvc3 . Can anyone help me ?
Requesting Gravatar... vivek Apr 10, 2012 4:28 PM
# re: Uploading a File (Or Files) With ASP.NET
Here is very simple article on file uploading in asp.net

http://sqldecode.blogspot.in/#!/2012/04/uploading-file-in-aspnet-example.html
Requesting Gravatar... ram Apr 16, 2012 5:39 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi,
thanks for the nice post,
How can I use confirm dialogue box to replace the file already exists..

Thanks,
Ram
Requesting Gravatar... Farid Apr 25, 2012 9:43 AM
# re: Uploading a File (Or Files) With ASP.NET MVC
Hi
How to test the upload file controller with and without moking the controller
Requesting Gravatar... dave May 02, 2012 12:17 PM
# re: Uploading a File (Or Files) With ASP.NET MVC
HttpPostedFileBase always getting null

<% using (Html.BeginForm("Attachment", "Attachment",FormMethod.Post, new { @id = "file",enctype="multipart/form-data" }))
{%>
<input name="file" type="file" />
<input type="submit" value="UploadFile" />
<%} %>


controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Attachment(HttpPostedFileBase file)
{
HttpFileCollectionBase files = ControllerContext.HttpContext.Request.Files;
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Attachment");
}

What do you have to say?

(will show your gravatar)
Please add 8 and 4 and type the answer here: