AJAX File Upload Using JQuery

In this article, we will look into file upload using JQuery plug-in. Ajax file upload plug-in allows us to upload files to server. I am going to explain it with an example. We will be using custom HTTP handler to upload file onto the server. Create an ASP.NET MVC web application and name it as JQueryFileUpload. Now, add below scripts to site.master:

  1. <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>   
  2. <script src="../../Scripts/ajaxupload.js" type="text/javascript"></script>   
Now, goto Index view under Home controller and add below html:
  1. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
  2.     <div id="uploadStatus" style="color: red;"></div>  
  3.     <input type="button" id="uploadFile" value="Upload File" />  
  4.     <div id="fileList"></div>  
  5. </asp:Content>  
We are using uploadStatus tag to show status message while uploading/deleting a file. uploadFile button is used to select the file to be uploaded. fileList tag is used to show list of files uploaded. Add a new class to the solution and name it as FileUploadHandler. This class will act as custom HTTP handler for uploading/deleting file. Add below code to the class:
  1. public class FileUploadHandler: IHttpHandler  
  2. {  
  3.   #region IHttpHandler Members  
  4.     public bool IsReusable {  
  5.         get {  
  6.             return false;  
  7.         }  
  8.     }  
  9.     public void ProcessRequest(HttpContext context) {  
  10.         try {  
  11.             //Uploaded File Deletion   
  12.             if (context.Request.QueryString.Count > 0) {  
  13.                 string filePath = @ "c:\DownloadedFiles\" + context.Request.QueryString[0].ToString();   
  14.                 if (File.Exists(filePath))  
  15.                     File.Delete(filePath);  
  16.             }  
  17.             //File Upload   
  18.             else {  
  19.                 string fileName = Path.GetFileName(context.Request.Files[0].FileName);  
  20.                 string location = @ "c:\DownloadedFiles\" + fileName;   
  21.                 context.Request.Files[0].SaveAs(location);  
  22.             }  
  23.         } catch {}  
  24.     }#endregion  
  25. }  
We implemented IHttpHandler and defined code to upload/delete file in ProcessRequest(). We are deleting a uploaded file by passing its name as parameter. We need to register the HTTP handler by adding below tag to web.config in httpHandlers section for any .upload request.
  1. <add path="*.upload" verb="*" type="JQueryFileUpload.FileUploadHandler"/>   
Now, add below script to site.master for making ajax call for upload/delete of the file.
  1. <script type="text/javascript">  
  2.     $(function() {  
  3.         //Function to upload file.   
  4.         new AjaxUpload('#uploadFile',  
  5.                        {  
  6.             action: 'FileUploadHandler.upload',  
  7.             name: 'upload',  
  8.             onComplete: function(file) {  
  9.                 $('<div><img src="../../Content/delete.jpg" style="width:20px;height:20px" class="delete"/>' + file + '</div>').appendTo('#fileList');  
  10.                 $('#uploadStatus').html("Upload Done.");  
  11.             },  
  12.             onSubmit: function(file, ext) {  
  13.                 if (!(ext && /^(txt|doc|docx|xls|pdf)$/i.test(ext))) {  
  14.                     alert('Invalid File Format.');  
  15.                     return false;  
  16.                 }  
  17.                 $('#uploadStatus').html("Uploading...");  
  18.             }  
  19.         });  
  20.         //Function to delete uploaded file in server.   
  21.         $('img').live("click"function() {  
  22.             $('#uploadStatus').html("Deleting");;  
  23.             deleteFile($(this));  
  24.         });  
  25.     });  
  26.   
  27.     function deleteFile(objfile) {  
  28.         $.ajax({  
  29.             url: 'FileUploadHandler.upload?del=' + objfile.parent().text(),  
  30.             success: function() {  
  31.                 objfile.parent().hide();  
  32.             }  
  33.         });  
  34.         $('#uploadStatus').html("Deleted");  
  35.     }  
  36. </script>  
We are using AjaxUpload function to upload file. We specified action as our HTTP handler and used onComplete and onSubmit events to show status of file upload. We are specifying file formats accepted for uploading in onSubmit event by its file extension. Finally, add below line to Global.asax under RegisterRoutes to skip routing for our HTTP handler:
  1. routes.IgnoreRoute("{file}.upload");   
Run the application, use Upload File button for selecting and uploading the file. Click on delete icon to delete corresponding file in the server.

I am ending the things here. I am attaching the source code with it. I hope this article will be helpful for all.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now