Upload Files To Server In ASP.NET

Introduction

In ASP.NET, there are multiple approaches developers follow to upload files to server. However, each will have its own limitations that developers find hard to fix. Here, I have detailed a simple approach to upload multiple files to server from ASP.NET MVC web application.

Getting Started

Step 1 - Create new ASP.NET MVC 4 Intranet Web Application “FileUploadDemo” with Razor engine

new

Step 2

Under FileUploadDemo project, open Views, Home, then Index.cshtml file. Delete all contents of the file and add the below lines of code,

  1. @Html.Hidden("FileUploadUrl", Url.Action("UploadFiles", "Home"))  
  2. <table>  
  3.     <tr>  
  4.         <td>  
  5.             <div id="uploadMsg"></div>  
  6.         </td>  
  7.     </tr>  
  8.     <tr>  
  9.         <td>  
  10.             <div>File One: </div>  
  11.             <div>  
  12.                 <input type="file" id="fileOne" name="files[0]" />  
  13.             </div>  
  14.         </td>  
  15.     </tr>  
  16.     <tr>  
  17.         <td>  
  18.             <div>File Two: </div>  
  19.             <div>  
  20.                 <input type="file" id="fileTwo" name="files[1]" />  
  21.             </div>  
  22.         </td>  
  23.     </tr>  
  24.     <tr>  
  25.         <td>  
  26.             <button type="button" id="btnUpload">UPLOAD FILES</button>                      
  27.         </td>  
  28.     </tr>  
  29. </table>  
The hidden field “FileUploadUrl” will have the controller action method to be called when the form data is submitted. Make sure that the name attribute of <input type=”file”> controls have the same name with sequential index values like files[0], files[1] and so on.

Step 3

Create new Index.js file under Scritps folder and add the below lines of code.
  1. $(document).ready(function () {  
  2.     $('#btnUpload').click(function () {  
  3.         var fileUploadUrl = $('#FileUploadUrl').val();  
  4.         var files = new FormData();  
  5.         var file1 = document.getElementById("fileOne").files[0];  
  6.         var file2 = document.getElementById("fileTwo").files[0];  
  7.         files.append('files[0]', file1);  
  8.         files.append('files[1]', file2);  
  9.   
  10.         $.ajax({  
  11.             type: 'POST',  
  12.             url: fileUploadUrl,  
  13.             data: files,  
  14.             dataType: 'json',  
  15.             cache: false,  
  16.             contentType: false,  
  17.             processData: false,  
  18.             success: function (response) {  
  19.                 $('#uploadMsg').text('Files have been uploaded successfully');  
  20.             },  
  21.             error: function (error) {  
  22.                 $('#uploadMsg').text('Error has occured. Upload is failed');  
  23.             }  
  24.         });  
  25.     });  
  26. });  
In the above code snippet, the files are retrieved through document.getElementById() method and the files are added in FormData object. Also, the controller action method path will be retrieved from “FileUploadUrl” hidden field in Index.cshtml file. Then the form data will be posted to server side controller action method “UploadFiles” of “Home” controller.

Step 4

Add the below statement at the first line of Index.cshtml file to include Index.js file,
  1. <script type="text/javascript" src="~/Scripts/jquery-1.7.1.min.js"></script>  
  2. <script type="text/javascript" src="~/Scripts/Index.js"></script>  
Step 5

Add the below key value pair under <appSettings> section in web.config file,
  1. <add key="UPLOAD_PATH" value="D:\WORKSPACE\WEB\"/>  
Step 6

Open UploadFileDemo, Controllers, then HomeController.cs file and add a new action method called “UploadFiles” with [HttpPost] attribute.
  1. [HttpPost]  
  2.         public ActionResult UploadFiles()  
  3.         {  
  4.             bool isSuccess = false;  
  5.             string serverMessage = string.Empty;  
  6.             var fileOne = Request.Files[0] as HttpPostedFileBase;  
  7.             var fileTwo = Request.Files[1] as HttpPostedFileBase;  
  8.             string uploadPath = ConfigurationManager.AppSettings["UPLOAD_PATH"].ToString();  
  9.             string newFileOne = Path.Combine(uploadPath, fileOne.FileName);  
  10.             string newFileTwo = Path.Combine(uploadPath, fileTwo.FileName);  
  11.   
  12.             fileOne.SaveAs(newFileOne);  
  13.             fileTwo.SaveAs(newFileTwo);  
  14.   
  15.             if (System.IO.File.Exists(newFileOne) && System.IO.File.Exists(newFileTwo))  
  16.             {  
  17.                 isSuccess = true;  
  18.                 serverMessage = "Files have been uploaded successfully";  
  19.             }  
  20.             else  
  21.             {  
  22.                 isSuccess = false;  
  23.                 serverMessage = "Files upload is failed. Please try again.";  
  24.             }  
  25.             return Json(new { IsSucccess = isSuccess, ServerMessage = serverMessage }, JsonRequestBehavior.AllowGet);  
  26.         }  
Step 7

Build the solution and run the web application. Browse any files and click on “UPLOAD FILES” button. The successful file upload screen will look as below,
 
output


Similar Articles