Upload Files to Server in ASP.NET MVC


In this article I will be demonstrating about the Upload functionality in ASP.NET MVC .

In MVC we don't use the FileUpload Server control as we did with Web Forms – So Let's explore in this article that How do we Upload Files to Server in ASP.Net MVC.

For demonstration here, I will be using Visual Studio 2010(MVC2.0)

  1. Create a new ASP.NET MVC2 Web application - name it as -say- UploadMVC
     
  2. For this sample application - Let's not create the unit test project.- So select the radio button - No, Do not create a unit Test Project.
     
  3. Now we have the readymade/default ASP.Net MVC2 Project template with few files already existing in each of the folders Model , View and Controller.
     
  4. Lets provide the Upload functionality in the existing Home Page (Views->Home->Index.aspx) – from where we can upload Files from client machine to Server.
     
  5. Go to Views->Home->Index.aspx

    Add below Lines of Code

    <div >
        <h2>Upload Files in MVC</h2>
       <% using (Html.BeginForm("FileUpload", "Home",
                        FormMethod.Post, new { enctype = "multipart/form-data" }))
            {%>
            <input name="uploadFile" type="file" />
            <input type="submit" value="Upload File"/>

            <span style="color:red;font-weight:bold">
            <%=TempData["UploadValidationMessage_Failure"]%>
            </span>

             <span style="color:Green;font-weight:bold">
             <%=TempData["UploadValidationMessage_Success"]%>
            </span>
    <%} %>
        </div>

    FileUpload – Action (in which Upload logic/Code is present) name which we will need to code in our Controller(HomeController.cs)

    Home-Controller Name
    enctype = "multipart/form-data" -make sure encoding type is multipart/form-data - This is required to support file uploads.

     

  6. Go to Controllers->HomeController.cs file

    a) Add using statement

    using System.IO;

    b) Include Action → FileUpload


    AcceptVerbs(HttpVerbs.Post)]
            public ActionResult FileUpload(HttpPostedFileBase uploadFile)
            {
                if (uploadFile != null)
                {

                    if (uploadFile.ContentLength > 0)
                    {
                        string strSuffixFileName = "_" + DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss").Replace("_", "");
                        string FilePath = HttpContext.Server.MapPath("../Uploads") + "\\ " + strSuffixFileName + "_" + Path.GetFileName(uploadFile.FileName);
                        uploadFile.SaveAs(FilePath);
                        TempData
    ["UploadValidationMessage_Success"] = "Data Upload Succeeded" + FilePath;
     
                        return View("Index");

                    }

                    return View("Index");
                }
     
                else
                {
                    TempData["UploadValidationMessage_Failure"] = "Please provide the filename to be uploaded";
                    return View("Index");
                }
     
            }

    UploadFile is of type HttpPostedFileBase which Serves as the base class for classes that provide access to individual files that have been uploaded by a client.

    ContentLength-gets the size of an uploaded file, in bytes.

    uploadFile.SaveAs-saves the contents of an uploaded file.

    Filename gets prefixed with the current date and time before getting saved in the folder – Uploads.

    Uploads- is the folder we need to create in Server – For testing purpose I have created it inside the Project folder in my client machine. - It can be seen if you download the Source Code .

    Filename gets prefixed with the current date and time before getting saved in the folder – Uploads.

    I have added 2 validations in the above Action Code-

    a) Say if user tries to Upload an empty file – he would get corresponding Validation message.
    b) Say if user doesn't selects a file and tries to upload - he would get corresponding Validation message.


    7. Run the application.
    a)

    MVC1.gif

    b) Click Browse-> Select the file to be uploaded and click Upload File – Once File is successfully uploaded in the folder Uploads – We would get the Success message as in below screen-shot.

    MVC2.gif

If our upload fails as per the 2 criteria mentioned as validations in Action Code – Corresponding message would be printed in the Index View.

Hope this article would be helpful for understanding Uploading files to Server in ASP.NET MVC.
I have attached the source code for this project.

Happy Learning!
 

Up Next
    Ebook Download
    View all
    Learn
    View all