File upload in ASP.NET MVC

Here is a sample for handling upload of a file, In your MVC application. In this sample i used the Dialog box of JQuery, where user will select the file and will click upload


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    

<h2>Files uploaded to server</h2>    

<div id="dialog" title="Upload files">        
    <% using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {%><br />
        <p><input type="file" id="fileUpload" name="fileUpload" size="23"/> ;</p><br />
        <p><input type="submit" value="Upload file" /></p>        
    <% } %>    
</div>
<a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Upload File</a>
</asp:content>


Then we have to handle this request in the respective controller which is specified in BeginForm of our above code (FileContoller) and action name (Upload). Following will be our code in the FileController Controller for the Upload action


public void Upload()
{
foreach (string inputTagName in Request.Files)
{
HttpPostedFileBase file = Request.Files[inputTagName];
if (file.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads")
, Path.GetFileName(file.FileName));
file.SaveAs(filePath);
}
}

RedirectToAction("Index", "File");
}


Download the sample code from here

File upload in MVC with JQuery Dialog

File upload in MVC with JQuery Dialog

About these ads
28 comments
  1. Binal said:

    hi,
    I’m working with mvc application.Problem is that, when i work with FileUpload control with mvc,i store filepath and name into database,so give me one example for uploading image file path and store that into database.

    • Binal said:

      Your comment is awaiting moderation.

      hi,
      I’m working with mvc application.Problem is that, when i work with FileUpload control with mvc,i store filepath and name into database,so give me one example for uploading image file path and store that into database.

      • A.Sethi said:

        If i am not wrong you want to upload the image with your MVC application and want to save the uploaded path in the database for the future reference. If this is the case then as you might have seen the sample there is one upload function. In that function you will get the file uploaded path, then with the help of you model part of the MVC Project (In my sample Model part is having LINQ) save that path in the database

        If you were asking some thing else please rectify me and i will try to give some solution as soon as possible

  2. Jerry said:

    Ran your example using firefox and after a couple of times testing the download, firefox consumes 50% of the processor as soon as I select the File Tab. Runs fine in IE.

    I get no indications what is wrong except the task managers shows firefox at the top of the process list and growing. Max’s out arounf 2500000

    • A.Sethi said:

      Thanks for information

      I will have a look to it and come back to you as soon as possible

  3. Gente, agrego una correccion al método Upload para que funcione como se debe.

    Queda corregido asi:

    public ActionResult Upload()
    {
    ….
    return RedirectToAction(“Index”, “File”);
    }

    Un saludo a todos y gracias por el ejemplo !!

    Antonino

    • A.Sethi said:

      Thanks for correcting me :)

    • Peter said:

      I have found the solution after some work.

      I changed the Upload() from
      public void Upload() to
      public ActionResult Upload()

      and then changed the last line of Upload() from RedirectToAction(“Index”, “File”); to
      return RedirectToAction(“Index”, “File”);

  4. Pingback: YOUR-TITLE

  5. Luke said:

    I noticed that when the image file name has a space in it then the image would not display correctly. One way that I fixed this is by in the Upload() method I added a replace to the file name.

    ;

  6. Luke said:

    string filePath = Path.Combine(HttpContext.Server.MapPath(“../Uploads”), Path.GetFileName(file.FileName.Replace(‘ ‘, ‘_’)));

  7. David said:

    I have an error message when i try to upload the file:

    Failure validation of the view state MAC. If a cluster or Web farm hosting this application, make sure that the configuration specifies the same validationKey the same algorithm and validation. AutoGenerate can not be used in a cluster.

    Can someone say me wath can i do in this case?

  8. Rodrigo said:

    Very nice. love it.

  9. TurboGen said:

    This is a really nice post – you did a great job explaining everything.

    I ran into the same problem that Antonino pointed out with the demo/download version.

    Thanks for your effort. :)

    • A.Sethi said:

      Thanks

  10. sefer said:

    did you try this upload method in firefox 3 or chrome, it does not work.

    thanks

  11. Vijay Kardile said:

    I am using Ajax.BeginForm() instead of Html.BeginForm().

    So juzz guide me, how to include [ enctype = “multipart/form-data” ]
    attribute in Ajax.BeginForm() ???
    please reply me soon….

    • Eric said:

      Not sure if this was already answered, but the link in the other reply was dead so I just wanted to throw this out there.

  12. Niraj said:

    Thanks for the nice post. A problem that drove me crazy which I wud like to share here to help some body. I used this with a content page, I did everything as mentioned here but no success, I was always getting my httppostedfilebase object as null. Finally I found my mistake, and that was very funny, the master page also had a form tag which was causing my contents page form tag to be ignored. Simply removing the form tag from my master page gave me success.

  13. Kalpesh said:

    I dont know if you will get a chance to read it but I have a question.
    I am using fileupload control along with some other controls.
    Its a form to create an object called Article.
    I want to upload file same with this object creation. so that the path where this file saved can be put into “article.ArticleFilePath”.

    I tried something like this but it gives file= null.
    public ActionResult Create(Article article, HttpPostedFileBase file)
    {
    }

  14. bharat said:

    thank

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: