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

asp.net mvc, asp.net, code 0 comments suggest edit

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

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

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);
  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"  />

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.

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);
  return RedirectToAction("Index");

Yes, it’s that easy. :)

Tags: aspnetmvc, upload

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.



131 responses

  1. Avatar for Andrei Rînea
    Andrei Rînea July 16th, 2010

    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)

  2. Avatar for Brian
    Brian July 17th, 2010

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

  3. Avatar for haacked
    haacked July 17th, 2010

    @andrei, thanks for the feedback. :)

  4. Avatar for Fynn
    Fynn July 18th, 2010

    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.

  5. Avatar for Kevin Major
    Kevin Major July 18th, 2010

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

  6. Avatar for Mike Henry
    Mike Henry July 18th, 2010

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

  7. Avatar for g
    g July 18th, 2010

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

  8. Avatar for Nick K
    Nick K July 18th, 2010

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

  9. Avatar for M
    M July 18th, 2010

    Thank you for keeping "simple" your focus. We all appreciate it!

  10. Avatar for Jordan
    Jordan July 18th, 2010

    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.

  11. Avatar for Phil
    Phil July 19th, 2010

    Thanks for the post. It is nice and simple.

  12. Avatar for Arun Mahendrakar
    Arun Mahendrakar July 19th, 2010

    Andrei Rinea, the answer to your second question is 'yes'. It does overwrite the first one.

  13. Avatar for bennyb
    bennyb July 21st, 2010

    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?

  14. Avatar for Tim Hobbs
    Tim Hobbs July 21st, 2010

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

  15. Avatar for haacked
    haacked July 21st, 2010

    @Tim You are correct. But in fairness to Nick, I made that change to the sample after Nick suggested it. :)

  16. Avatar for Imranhussein
    Imranhussein July 22nd, 2010

    @Nick, @haacked
    we can validate the file and allow only to upload allowed file ext. Isn't it?

  17. Avatar for Morin
    Morin July 25th, 2010

    I have a question and not able to get it answered.
    I would highly appreciate if anybody can answer this.

  18. Avatar for bennyb
    bennyb July 26th, 2010

    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.

  19. Avatar for Rony
    Rony July 26th, 2010

    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?

  20. Avatar for Chirag Nirmal
    Chirag Nirmal July 27th, 2010

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

  21. Avatar for Romero Brito
    Romero Brito July 29th, 2010

    Any ideas about how to get "asynchronous upload progress report" using this technique (for large file uploads)?

  22. Avatar for Joshua Hayes
    Joshua Hayes July 29th, 2010

    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!

  23. Avatar for Joshua Hayes
    Joshua Hayes July 29th, 2010

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

  24. Avatar for Thanigainathan
    Thanigainathan July 29th, 2010

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

  25. Avatar for duffy
    duffy August 3rd, 2010

    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?

  26. Avatar for rakesh
    rakesh September 2nd, 2010

    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

  27. Avatar for Eric Dorothy
    Eric Dorothy September 27th, 2010

    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?

  28. Avatar for Eric Dorothy
    Eric Dorothy September 28th, 2010

    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.

  29. Avatar for Berin Loritsch
    Berin Loritsch October 6th, 2010

    To answer the questions about forms with mixed data (files and text fields), I believe I have the answer:
    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.

  30. Avatar for Joemarie Amparo
    Joemarie Amparo October 6th, 2010

    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

  31. Avatar for snatty
    snatty November 15th, 2010

    Thank a lot for code.It's do work. Thank you

  32. Avatar for Jerry
    Jerry December 27th, 2010

    Hello ...
    I am Taiwan boy .
    my name is Jerry.
    thank you !
    no books to learn ASP.NET MVC.
    nice article !! thx...

  33. Avatar for Phil
    Phil January 3rd, 2011

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

  34. Avatar for JT
    JT February 2nd, 2011

    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

  35. Avatar for ChinaBoy
    ChinaBoy May 2nd, 2011

    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.

  36. Avatar for supreet
    supreet May 20th, 2011

    thanks for the code.It rly works.

  37. Avatar for Shailen
    Shailen June 8th, 2011

    Hi Scott,
    I am newby to MVC. This is nice article, but can we make something like this:
    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.

  38. Avatar for Ben
    Ben June 12th, 2011

    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.
    public ActionResult Index(FormCollection form, HttpPostedFileBase file) {

  39. Avatar for arun
    arun July 4th, 2011

    hi this is working for me.thanks a lot.but what should be done to validate the file types withou a model

  40. Avatar for Manoj
    Manoj August 25th, 2011

    I Have to Upload multiple images in Sql database and retrive it to display to view page.

    please help me
    Thanks in advance

  41. Avatar for Abhay Dubey
    Abhay Dubey September 4th, 2011

    Can I save Two same name images on a same folder by uploading images from different users?????????

  42. Avatar for Srikanth
    Srikanth September 14th, 2011

    I need code for binding the upload files to view and downloading that files.

  43. Avatar for Muhammad Arif
    Muhammad Arif October 13th, 2011

    That is nice way. Good!

  44. Avatar for prashant
    prashant November 4th, 2011


  45. Avatar for Themhs
    Themhs November 21st, 2011

    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?

  46. Avatar for Vinca
    Vinca December 2nd, 2011

    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.

  47. Avatar for Rajesh
    Rajesh December 21st, 2011

    small files upload is okay

    when i upload large files it's not working.

  48. Avatar for Edwin
    Edwin December 27th, 2011

    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.

  49. Avatar for Zeesahn Umar
    Zeesahn Umar January 12th, 2012

    Really nice and simple tutorial

  50. Avatar for nice article..
    nice article.. January 15th, 2012

    It's very helpful to upload multiple images in mvc...

  51. Avatar for aman
    aman January 19th, 2012

    i hav a problem .
    how to design app_data/uploads where the file will b stored

  52. Avatar for Hashcoderz
    Hashcoderz February 17th, 2012

    If the selected file name contains '&#', the upload will fail. Do we have any workaround for this.

  53. Avatar for anonymous
    anonymous February 18th, 2012

    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.

  54. Avatar for Anonymous
    Anonymous March 29th, 2012

    Great post! Thanks. And yes it's now #1 on google!

  55. Avatar for Ahsan
    Ahsan April 10th, 2012

    Guys , i need to upload images using ajax in mvc3 . Can anyone help me ?

  56. Avatar for vivek
    vivek April 10th, 2012

    Here is very simple article on file uploading in asp.net

  57. Avatar for ram
    ram April 16th, 2012

    thanks for the nice post,
    How can I use confirm dialogue box to replace the file already exists..

  58. Avatar for Farid
    Farid April 25th, 2012

    How to test the upload file controller with and without moking the controller

  59. Avatar for dave
    dave May 2nd, 2012

    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" />
    <%} %>

    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);
    // redirect back to the index action to show the form once again
    return RedirectToAction("Attachment");

  60. Avatar for BK
    BK May 31st, 2012

    In order to restrict the type of files users couple upload (e.g. I only want them to upload word documents in this case), I used the following code. I think it could be tweaked for folks wanting image directories, etc.
    if (file.ContentLength > 0 && (Path.GetExtension(file.FileName) == (".doc") || Path.GetExtension(file.FileName) == ".docx"))
    This way I can put it whereever I want.

  61. Avatar for Jules Bartow
    Jules Bartow June 11th, 2012

    Mr. Haack you have the knack. Most excellent brilliant kind sir. Do you have as sterling and simple demo to show how to save a reference in SQL Server to the image location and image type for the user that uploaded the images using Entity Framework DbContext. I know how to do it with stored procedure inserts returning a primary key and inserting ImageId and UserId into an associate many-to-many table.
    Doing it elegantly and simply in EF is elusive.

  62. Avatar for Harry
    Harry June 27th, 2012

    Would anyone be able to convert the above to work in MVC3 please? I'm getting errors when trying to use the code above in Visual Web Dev 2010, MVC3 Razor....

  63. Avatar for James
    James July 13th, 2012

    Love your site and this example is great I used it for the upload files method on my site but unfortunately, I am having trouble with the files being overwritten just like some of the other commentors here is what I wrote that doesn't work but I think I might be close!
    public String Uploadfile(HttpPostedFileBase file)
    if (file != null && file.ContentLength > 0)
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
    string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
    int iteration = 1;
    while (System.IO.File.Exists(Server.MapPath(fileName)))
    fileName = string.Concat(fileNameWithoutExtension, "-", iteration);
    return file.FileName;

  64. Avatar for Yalidion
    Yalidion July 16th, 2012

    Very simple and nice.

  65. Avatar for James
    James July 16th, 2012

    I managed to figure out how to attach a file that already exists in the upload directory without overwriting the previous file. I thought I would update the code I posted last week with code that completely works in MVC 3. Hope this helps everyone else solve this issue!
    public String Uploadfile(HttpPostedFileBase file)
    if (file != null && file.ContentLength > 0)
    var fileName = Path.GetFileName(file.FileName);
    var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
    string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(file.FileName);
    int iteration = 1;
    while (System.IO.File.Exists((path)))
    fileName = string.Concat(fileNameWithoutExtension, "-", iteration, System.IO.Path.GetExtension(file.FileName));
    path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
    return file.FileName;

  66. Avatar for Pavan Gayakwad
    Pavan Gayakwad July 17th, 2012

    Cool article, It overlooked to attract attention towards server upload limits and IIS size settings.

  67. Avatar for ggarcia
    ggarcia August 27th, 2012

    Thanks a lot, this article is very useful!!!

  68. Avatar for Bilal
    Bilal September 3rd, 2012

    public ActionResult ParsedRequisition(HttpPostedFileBase file, Web.Areas.ViewModel.AddRequisitionViewModel addReq)

    if (file != null && file.ContentLength > 0)
    System.IO.DirectoryInfo myDirectory = new System.IO.DirectoryInfo(Server.MapPath("~/files"));
    FileInfo[] fileList = myDirectory.GetFiles();
    int count = fileList.Length;
    if (count == 0)
    file.SaveAs(Server.MapPath("~/files/" + file.FileName));
    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
    object miss = System.Reflection.Missing.Value;
    object path = Server.MapPath("~/files/" + file.FileName);
    object readOnly = true;
    string body=string.Empty;
    Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
    for (int i = 0; i < docs.Paragraphs.Count; i++)
    body+= docs.Paragraphs[i + 1].Range.Text.ToString();
    body += "<br />";

  69. Avatar for stephan
    stephan September 9th, 2012
  70. Avatar for Clay Smith
    Clay Smith September 15th, 2012

    Thanks! Although this didn't work for me, I just used Hanselman's Request.Files method. See here: claysdev.com

  71. Avatar for ashutosh
    ashutosh October 1st, 2012

    excellent stuff.help me a lotttt
    reaaly thanks

  72. Avatar for Squid
    Squid November 6th, 2012

    Wow, over two hours of working out how to do this and the 10 minutes of reading your article and its done.
    Thank you so much.

  73. Avatar for Keith Yanachik
    Keith Yanachik November 16th, 2012

    Thank you, this worked perfect. I put the HttpPostedFileBase as a public property called File in my model. Was able to then take put the IO stream into a Mail attachment and email the file.
    System.Net.Mail.Attachment mailAttachment = new System.Net.Mail.Attachment(formVals.File.InputStream, formVals.File.FileName);

  74. Avatar for MJ
    MJ December 7th, 2012

    Thanks for the good article.
    My requirement is to allow the user to select multiple files from a folder in a single step instead of adding file one by one using the multiple browse buttons.
    Any ideas how can I implement that.

  75. Avatar for bot
    bot December 26th, 2012

    Nice example..!! but Is there a way to edit/change the picture base on your example? I'm sorry I'm pretty new to MVC.. :) thanks in advance

  76. Avatar for Tanx
    Tanx January 22nd, 2013

    Thank you, It was a great post and helped me alot.

  77. Avatar for Moumit Mondal
    Moumit Mondal January 29th, 2013

    Thanks man ...... it was very cool for a beginner like me ......

  78. Avatar for anish222
    anish222 January 30th, 2013

    Thanks.. Its really Nice.

  79. Avatar for Fred Wilson
    Fred Wilson February 9th, 2013

    With all due respect, I think  Scott Hanselman’s blog post is more informative. The extra information he posted on what actually goes underneath file upload is so worth much more than the small code fragment posted here though it still gets the job done.

  80. Avatar for berthely
    berthely February 27th, 2013

    this is awesome, thanks for the tutorial.

  81. Avatar for Nik
    Nik March 4th, 2013

    When uploading multiple files, how can I check the ID of each files originating input box so that I can upload each to a different location? ie: if id=file1 save to X, file2 save to Y, file3 save to Z.

  82. Avatar for Michael Harper
    Michael Harper March 10th, 2013

    Great post :)

  83. Avatar for Anusha
    Anusha May 22nd, 2013

    It worked perfect. Thanks for such a good article.

  84. Avatar for royceroy
    royceroy June 5th, 2013

    This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.



  85. Avatar for Udhaya
    Udhaya August 22nd, 2013

    It is really amazing and simple.. I search many links but this is simple and worth..Thanks..

  86. Avatar for bitdancer
    bitdancer August 24th, 2013

    nice post! works fine. thank you.

  87. Avatar for anil
    anil September 11th, 2013

    This is my actual code ,Edit multiple images successfully edited,

    1) At the time of Edit single image not edited

    public ActionResult Edit(int id, Product collection, HttpPostedFileBase[] MultipleFiles)
    Product p = db.Products.Single(e => e.TagID == id);
    //List<string> blobs = new List<string>();

    if (MultipleFiles != null)
    foreach (var fileBase in MultipleFiles)
    if (fileBase != null && fileBase.ContentLength > 0)
    // Retrieve a reference to a container
    CloudBlobContainer blobContainer = _myBlobStorageService.GetCloudBlobContainer();
    CloudBlob blob = blobContainer.GetBlobReference(fileBase.FileName);

    // Create or overwrite the "myblob" blob with contents from a local file
    List<string> blobs = new List<string>();

    foreach (var fileBase in MultipleFiles)
    CloudBlobContainer blobContainer1 = _myBlobStorageService.GetCloudBlobContainer();
    CloudBlob blob1 = blobContainer1.GetBlobReference(fileBase.FileName);
    //p.Image = blob1.Uri.ToString();

    p.Image = blobs.ElementAt(0).ToString();
    p.Image1 = blobs.ElementAt(1).ToString();
    // TODO: Add update logic here
    //p.Image = collection.Image;
    p.Name = collection.Name;
    p.Price = collection.Price;
    p.Description = collection.Description;
    //p.Image = collection.Image;
    // p.Image1 = collection.Image1;
    return RedirectToAction("Index");


  88. Avatar for Dylanett
    Dylanett October 19th, 2013

    Make sure you include:

    using System.IO;

    At the top of your controller class.

  89. Avatar for Lab5Connect
    Lab5Connect October 28th, 2013

    Nice article

  90. Avatar for Lab5Connect
    Lab5Connect October 28th, 2013

    Is it possible to call via ajax call

  91. Avatar for Imran
    Imran November 30th, 2013

    very helpful post

  92. Avatar for Sathish Kumar
    Sathish Kumar January 8th, 2014

    I want to store that file path in the database.
    can u please help me?
    plz send me the code.

  93. Avatar for b
    b January 13th, 2014

    in above code
    Path name does not exist in cuurent context..error msg
    helpme out

  94. Avatar for Dale Waring
    Dale Waring January 15th, 2014

    Great article helped me a lot but my only issue with it is where you're storing the files, I'd recommend to anyone following the tutorial to create a folder in your solution for example images, then a sub folder called uploads and then replace App_Data with images in the path.

    Just the App_Data folder is meant to be used for database files not images, documents etc.

    All in all though spot on.


  95. Avatar for Elyor Latipov
    Elyor Latipov January 25th, 2014

    +1 thx....

  96. Avatar for Krunal
    Krunal April 3rd, 2014

    What about uploading files to windows Azure hosted website, as this will not allow to upload any file in Azure Websites. Have you got any solution for that. I need Help.

  97. Avatar for buttercatz99
    buttercatz99 April 4th, 2014

    Gold Standard? The link doesn't even render. Never heard of it. Hardly a "gold standard".

  98. Avatar for Krunal
    Krunal April 10th, 2014

    Great Post. Now do it from Partial View. Lets see how it works.

  99. Avatar for Bill Jenkins
    Bill Jenkins April 25th, 2014

    You're kidding, right?

  100. Avatar for Santhosh Kumar Chandran
    Santhosh Kumar Chandran May 12th, 2014

    If i have some model properties in the view then what would be the parameter that i'll pass in the ActionResult?

  101. Avatar for ViniKatyal
    ViniKatyal May 26th, 2014

    What if we have multiple files?

  102. Avatar for Rian Mostert
    Rian Mostert May 27th, 2014

    Nice Post, thank you very much!

  103. Avatar for Ghuk
    Ghuk June 3rd, 2014

    You should use IEnumerable<httppostedfilebase> as a parameter type in your controller action. This is mentioned in the post.

  104. Avatar for vinay
    vinay June 13th, 2014

    This is really really nice article.


  105. Avatar for CaRDiaK
    CaRDiaK February 2nd, 2015

    I thought this would be all that's needed, but now my HttpPostedFileBase is null. Any ideas?

  106. Avatar for CaRDiaK
    CaRDiaK February 2nd, 2015

    OK I found out that to transfer files you must have enctype = "multipart/form-data".

    So to access the file including the FormCollection use the following in the view (then your signature is valid on the controller and you won't get a null file);

    @using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))

  107. Avatar for Vinicius Augusto
    Vinicius Augusto March 21st, 2015

    very good! thanks! simple and the best! congratulations! brazil

  108. Avatar for Roberto Lopez
    Roberto Lopez March 30th, 2015

    I was hoping there would be code for file validation e.g. only allow xlsx files which is what I'm struggling with right now.

  109. Avatar for James Mackie
    James Mackie May 15th, 2015

    I ive copy pasted this example into VS2013 with .net framework 4.5 and I get the following exception ~/App_Data/uploads\th1R1W52JG.jpg' is not rooted.

  110. Avatar for Tzvika
    Tzvika May 15th, 2015

    Thanks a lot for this post, very helpful. It works great with IE but with the exact same code and file it somehow fails with Chrome. The passed path from the browser is C:\\Program Files (x86)\\IIS Express\\<myfile> instead of its correct location. Any ideas?

  111. Avatar for Salman Samian
    Salman Samian June 14th, 2015

    Thanks about spread this article , but if it is possible put an article about validating POSTED file.

  112. Avatar for sgv
    sgv July 14th, 2015


  113. Avatar for harshil gandhi
    harshil gandhi September 23rd, 2015

    thanks admin.... it works gr8.....

  114. Avatar for Erick Wendel
    Erick Wendel January 13th, 2016

    Thanks !!

  115. Avatar for Rajeev Jha
    Rajeev Jha February 10th, 2016

    Great Example Dude.
    IEnumerable<httppostedfilebase> files in Action Method Parameter stores Data as an Array[0],[1] So we need to looping to get file one by one or foreach(var file in files){Code Goes Here }.

  116. Avatar for Rajeev Jha
    Rajeev Jha February 10th, 2016

    Good Job.

  117. Avatar for Rajeev Jha
    Rajeev Jha February 10th, 2016

    public ActionResult Edit(int id, Product collection, HttpPostedFileBase[] MultipleFiles)
    if (MultipleFiles != null)
    foreach (var fileBase in MultipleFiles)
    //Code Goes Here

  118. Avatar for Taz
    Taz February 11th, 2016

    Recycling the app pool effectively restarts your site because the IIS worker process gets restarted. Do not restart the process while users are on the site

  119. Avatar for Fabricio Leite
    Fabricio Leite April 22nd, 2016

    Simples mas eficiente, obrigado!

  120. Avatar for Vijay Saklani
    Vijay Saklani April 24th, 2016


    rally its a nice article...

  121. Avatar for Ronald Grabulan
    Ronald Grabulan September 3rd, 2016

    Hi, I am a newbie here . Is it Possible to upload the file to another server ? thanks in advance

  122. Avatar for Asad Ali
    Asad Ali December 8th, 2016

    if i have array of images stored in the folder then how can i update them...lets say a student can have multiple array of images stored in a folder and assume that we want to update just the 3rd image..then how may i do that...please tell me

  123. Avatar for Секул Камберов
    Секул Камберов April 21st, 2017

    Awesome :)

  124. Avatar for mj soma
    mj soma April 26th, 2017


  125. Avatar for Ted Driver
    Ted Driver January 31st, 2018

    You won. Your post came up first, I never saw Scott's. Congrats!

  126. Avatar for Ivirson Daltro
    Ivirson Daltro February 23rd, 2018

    Something so simple and I could not solve it. Thank you for helping me!

  127. Avatar for navyjax2
    navyjax2 March 28th, 2018

    Need to check to see if "file" is null first, in that first example, or you'll get an unhandled exception when checking its ContentLength and the object is null. Same with "files" in that second example, as you can't iterate something that is null.

  128. Avatar for Irakli Gigiberia
    Irakli Gigiberia May 24th, 2018

    You should also add in this article how to use this logic for one or multiple file upload inputs with multiple attribute, I met this code multiple times and it'd be nice to have that information at once next time I come here )) Thanks in advance

  129. Avatar for Adeola
    Adeola June 27th, 2018

    i have an error of object instance when trying to use this code for multiple files upload

  130. Avatar for Ronald
    Ronald November 1st, 2018

    Well I am trying this thing multiple times but still HttpPostedFileBase return Null

  131. Avatar for Abdul Nasir Khan
    Abdul Nasir Khan November 27th, 2018

    how to pass null value as input file