One of the very common task in web application is allowing user to upload files from the client machine to Server. usually files are uploaded along with a form submission. But using JQuery and Ajax we can accomplish this task without the entire page post back.In such cases, you can allow a user to select files using the FileUpload server control of ASP.NET and then upload those files to the server through an Ajax request to a generic handler.

Requirement
  1. Web form
  2. JQuery
  3. Generic handler
Web form
The following web form consists of a file upload control,user can select the file using file upload control and then they click the upload button to upload the selected file to server.
  1. <h3>Upload File using Jquery AJAX in Asp.net</h3>
  2. <table>
  3. <tr>
  4. <td>File:</td>
  5. <td>
  6. <asp:FileUpload ID="fupload" runat="server" onchange='prvimg.UpdatePreview(this)' /></td>
  7. <td><asp:Image ID="imgprv" runat="server" Height="90px" Width="75px" /></td>
  8. </tr>
  9. <tr>
  10. <td></td>
  11. <td><asp:Button ID="btnUpload" runat="server" cssClass="button" Text="Upload Selected File" /></td>
  12. </tr>
  13. </table>
JQuery
  1. $("#btnUpload").click(function (evt) {
  2. var fileUpload = $("#fupload").get(0);
  3. var files = fileUpload.files;
  4. var data = new FormData();
  5. for (var i = 0; i < files.length; i++) {
  6. data.append(files[i].name, files[i]);
  7. }
  8. $.ajax({
  9. url: "FileUploadHandler.ashx",
  10. type: "POST",
  11. data: data,
  12. contentType: false,
  13. processData: false,
  14. success: function (result) { alert(result); },
  15. error: function (err) {
  16. alert(err.statusText)
  17. }
  18. });
  19. evt.preventDefault();
  20. });
FileUploadHandler.ashx
  1. <%@ WebHandler Language="C#" Class="FileUploadHandler" %>
  2. using System;
  3. using System.Web;
  4. public class FileUploadHandler : IHttpHandler
  5. {
  6. public void ProcessRequest (HttpContext context)
  7. {
  8. if (context.Request.Files.Count > 0)
  9. {
  10. HttpFileCollection files = context.Request.Files;
  11. for (int i = 0; i < files.Count; i++)
  12. {
  13. HttpPostedFile file = files[i];
  14. string fname = context.Server.MapPath("~/uploads/" + file.FileName);
  15. file.SaveAs(fname);
  16. }
  17. context.Response.ContentType = "text/plain";
  18. context.Response.Write("File Uploaded Successfully!");
  19. }
  20. }
  21. public bool IsReusable
  22. {
  23. get
  24. {
  25. return false;
  26. }
  27. }
  28. }
Output
file upload
Reference: Asynchronous file upload using jquery in ASP.NET.