In this article, I am going to demonstrate you, how to upload file in ASP.NET MVC C# (you will see both, single or multiple files upload examples in ASP.NET MVC C# ), if you are looking for image upload you can take a look at this question https://qawithexperts.com/questions/14/how-to-upload-image-in-c-mvc.

Let's understand File Upload Basics in ASP.NET MVC C#

During the file upload process, only two parts of the MVC model interact with each other – a view and a controller. Let’s examine the file upload process step by step:

  1. A user visits a web page with an uploader (represented by View) and chooses files to be uploaded.
  2. When the upload is started, the uploader packs the files into a POST request and sends this request to the server.
  3. ASP.NET caches all data in server memory or to disk depending on the uploaded file size.
  4. ASP.NET MVC defines the controller and appropriate action method that will handle the request.
  5. The action method handles the request (for example, saves files on a hard disk, or updates a database, etc.) through the Controller.Request property, which gets the HttpPostedFilesBase object for the current request.
  6. ASP.NET MVC sends an answer to the client through Controller.Response.

You can configure file upload settings by specifying appropriate attributes in the web.config (or machine.config if you want to make server-wide changes). Let’s see what attributes are used to limit the file upload:

  • maxRequestLength – the request size limit in kilobytes (the default value is 4096 KB).
  • requestLengthDiskThreshold – the limit of data buffered in the server memory in kilobytes (the default value is 80 KB).
  • executionTimeout – the allowed execution time for the request before being automatically shut down by ASP.NET (the default value is 110 seconds).

All these attributes should be specified in the <httpRuntime> section.

Single File Upload in ASP.NET MVC, Step by Step Implementation

Now let's create a Project in Visual Studio to upload file

  1. Go to File->New->Project. Give a suitable name to the Application. Click OK.

    File-Upload-MVC C#
  2. Select MVC Template from it

    MVC-template-File-upload-Csharp
  3. Now Let's add a folder to upload files on this Folder of the project.

    Upload-file-mvc-folder
  4. Now let's Add a controller (UploadFileController) and the Code in it to handle post request and handle File Upload

    Add-Controller-MVC.png

    Click on 'Add' and then name it (UploadFileController), add this code now

    [HttpPost]  
    public ActionResult Upload(HttpPostedFileBase file)  
    {  
        if (file != null && file.ContentLength > 0)  
            try 
            {  //Server.MapPath takes the absolte path of folder 'Uploads'
                string path = Path.Combine(Server.MapPath("~/Uploads"),  
                                           Path.GetFileName(file.FileName));  
               //Save file using Path+fileName take from above string
                file.SaveAs(path);  
                ViewBag.Message = "File uploaded successfully";  
            }  
            catch (Exception ex)  
            {  
                ViewBag.Message = "ERROR:" + ex.Message.ToString();  
            }  
        else 
        {  
            ViewBag.Message = "You have not specified a file.";  
        }  
        return View();  
    }

    Note: You may need to Add System.IO reference in the above Controller

  5. Add the Index View (Right click inside Index ActionMethod and then 'Add' View), for creating File-upload handler in HTML, and then add the code below to in your view

    <h2>UploadFile</h2>  
       
    @using (Html.BeginForm ("Upload",  
                            "UploadFile",  
                            FormMethod.Post,  
                            new { enctype = "multipart/form-data" }))  
    {                    
        <label for="file">Upload File:</label>  
        <input type="file" name="file" id="file"/><br><br>  
        <input type="submit" value="Upload"/>  
        <br><br>  
        @ViewBag.Message  
    }

    Output-Index-page.png
    Above image shows the output of the View.
    Note: Always remmeber to add "enctype = "multipart/form-data"" in your HTML form, if you forget to write this piece of code in your HTML, your files will not be submitted on the C# controller.

  6. In you browser view, browse a file using 'Choose File' button and try to upload a file by clicking 'Upload' button, here is the debugging screenshot of file uploading, which shows, file was uploaded successfully

    Debugging-file-upload-mvc-c

That's you are done, check the 'Uploads' Folder in your project, you should found the file there

file-in-upload-folder-after-uploading-it.png

Note: The above code doesn't implement any security, you should scan your uploaded file using Viruses for better security

Multiple File Upload in ASP.NET MVC C#

The above example shows to upload single file in asp.net MVC, so basically we would have to loop multiple file uploads in C# code, while in front end make our HTML to multiple files, here are the changes which you need to do in C#

        [HttpPost]  //Now we are getting array of files check sign []
        public ActionResult UploadFiles(HttpPostedFileBase[] files)  
        {  
          
          //iterating through multiple file collection   
                foreach (HttpPostedFileBase file in files)  
                {  
                    //Checking file is available to save.  
                    if (file != null)  
                    {  
                        var InputFileName = Path.GetFileName(file.FileName);  
                        var ServerSavePath = Path.Combine(Server.MapPath("~/Uploads/") + InputFileName);  
                        //Save file to server folder  
                        file.SaveAs(ServerSavePath);  
                        //assigning file uploaded status to ViewBag for showing message to user.  
                        ViewBag.UploadStatus = files.Count().ToString() + " files uploaded successfully.";  
                    }  
   
                }  
             
            return View();  
        }  

In the above code, since we are uploading files at once, we are passing HttpPostedFileBase array of files, then iterating each file using foreach loop, and saving file on server folder ("Uploads").

In HTML/View udpated .cshtml code will be like below

<br/>
@using (Html.BeginForm("UploadFiles", "UploadFile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <div class="form-horizontal">
      
        <div class="form-group">
           <div class="col-lg-2">Browse Files</div>
            <div class="col-md-10">
              <input type="file" multiple name="files" id="Files" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Upload" class="btn btn-primary" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10 text-success">
                @ViewBag.UploadStatus
            </div>
        </div>

    </div>
}  

if you will notice, we have just added multiple an attribute in <input type='file'>above HTML code, to make it select multiple files, here is the sample View image

Multiple-file-upload-mvc

After selecting all file and clicking on Upload, here is the image of Controller while debugging, you can see we have got 3 files in Controller this time

multiple-file-upload-asp-net-mvc

That's it, we are done.

You may also like to read

File uploading using DropZone js & HTML5 in MVC

File Uploading using jQuery Ajax in MVC (Single or multiple file upload)

File upload in ASP.NET Core MVC (Single or Multiple files)

That's it we are done, feel free to post your comments on the above article or ask any questions related to file uploading in ASP.NET MVC.