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

Let's understand File Upload Nuts in ASP.Net MVC C#

During the file upload procedure, just 2 parts of the MVC model interact with each other – a view and a controller. Let'due south examine the file upload process step past step:

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

Yous can configure file upload settings by specifying appropriate attributes in the web.config (or machine.config if you lot desire to make server-wide changes). Let's meet 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 retentiveness in kilobytes (the default value is 80 KB).
  • executionTimeout – the immune execution time for the request before being automatically shut down by ASP.Internet (the default value is 110 seconds).

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

Single File Upload in ASP.NET MVC, Footstep by Pace Implementation

At present allow'southward create a Projection 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'due south 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 lawmaking now

                  [HttpPost]   public ActionResult Upload(HttpPostedFileBase file)   {       if (file != aught && 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 = "Mistake:" + ex.Message.ToString();           }       else      {           ViewBag.Message = "You have not specified a file.";       }       return View();   }            

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

  5. Add the Index View (Right click inside Index ActionMethod and then 'Add together' 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/grade-data" }))   {                         <label for="file">Upload File:</label>       <input blazon="file" proper name="file" id="file"/><br><br>       <input type="submit" value="Upload"/>       <br><br>       @ViewBag.Message   }            

    Output-Index-page.png
    To a higher place prototype shows the output of the View.
    Annotation: Always remmeber to add "enctype = "multipart/class-information"" 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 yous browser view, scan a file using 'Choose File' button and try to upload a file by clicking 'Upload' push button, here is the debugging screenshot of file uploading, which shows, file was uploaded successfully

    Debugging-file-upload-mvc-c

That'due south you are done, check the 'Uploads' Folder in your project, y'all should found the file at that place

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

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

Multiple File Upload in ASP.Internet MVC C#

The to a higher place example shows to upload single file in asp.cyberspace MVC, then basically we would have to loop multiple file uploads in C# code, while in front cease make our HTML to multiple files, here are the changes which y'all need to practise 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);                           //Relieve file to server binder                           file.SaveAs(ServerSavePath);                           //assigning file uploaded condition 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 one time, we are passing HttpPostedFileBase assortment of files, then iterating each file using foreach loop, and saving file on server binder ("Uploads").

In HTML/View udpated .cshtml lawmaking will be like beneath

          <br/> @using (Html.BeginForm("UploadFiles", "UploadFile", FormMethod.Mail service, new { enctype = "multipart/form-data" })) {      <div grade="form-horizontal">                <div class="form-group">            <div class="col-lg-ii">Browse Files</div>             <div class="col-md-10">               <input type="file" multiple name="files" id="Files" />             </div>         </div>         <div class="course-grouping">             <div form="col-md-offset-ii col-dr.-10">                 <input type="submit" value="Upload" class="btn btn-master" />             </div>         </div>         <div class="form-group">             <div class="col-doctor-offset-ii col-md-10 text-success">                 @ViewBag.UploadStatus             </div>         </div>      </div> }                  

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

Multiple-file-upload-mvc

Subsequently selecting all file and clicking on Upload, here is the epitome of Controller while debugging, you can run into we take got iii files in Controller this time

multiple-file-upload-asp-net-mvc

That's it, we are done.

You may too 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 Cadre MVC (Single or Multiple files)

That's it we are done, feel free to mail your comments on the in a higher place article or ask whatsoever questions related to file uploading in ASP.NET MVC.