How To Upload File Without PostBack In ASP.NET

In this article, I am going to explain how to upload a file with the help of "Handler" in ASP. NET C#. My main focus to write this blog is that, if you work with file upload control, the page requires full PostBack and if your file upload control is inside the update panel, you must specify your submit button in trigger, as shown below.

  1. <Triggers>  
  2.    <asp:PostBackTrigger ControlID=""/>  
  3. </Triggers>  
This also causes the full PostBack problem. To remove this problem, use "Handler" in ASP. NET C#.

UploadFile.ashx Code
  1. using System;  
  2. using System.Web;  
  3. using System.IO;  
  4. using System.Web.SessionState;  
  5. public class UploadFile: IHttpHandler, IRequiresSessionState {  
  6.     public void ProcessRequest(HttpContext context) {  
  7.         string filedata = string.Empty;  
  8.         if (context.Request.Files.Count > 0) {  
  9.             HttpFileCollection files = context.Request.Files;  
  10.             for (int i = 0; i < files.Count; i++) {  
  11.                 HttpPostedFile file = files[i];  
  12.                 if (Path.GetExtension(file.FileName).ToLower() != ".jpg" &&  
  13.                     Path.GetExtension(file.FileName).ToLower() != ".png" &&  
  14.                     Path.GetExtension(file.FileName).ToLower() != ".gif" &&  
  15.                     Path.GetExtension(file.FileName).ToLower() != ".jpeg" &&  
  16.                     Path.GetExtension(file.FileName).ToLower() != ".pdf"  
  17.                 ) {  
  18.                     context.Response.ContentType = "text/plain";  
  19.                     context.Response.Write("Only jpg, png , gif, .jpeg, .pdf are allowed.!");  
  20.                     return;  
  21.                 }  
  22.                 decimal size = Math.Round(((decimal) file.ContentLength / (decimal) 1024), 2);  
  23.                 if (size > 2048) {  
  24.                     context.Response.ContentType = "text/plain";  
  25.                     context.Response.Write("File size should not exceed 2 MB.!");  
  26.                     return;  
  27.                 }  
  28.                 string fname;  
  29.                 if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") {  
  30.                     string[] testfiles = file.FileName.Split(new char[] {  
  31.                         '\\'  
  32.                     });  
  33.                     fname = testfiles[testfiles.Length - 1];  
  34.                 } else {  
  35.                     fname = file.FileName;  
  36.                 }  
  37.                 //here UploadFile is define my folder name , where files will be store.  
  38.                 string uploaddir = System.Configuration.ConfigurationManager.AppSettings["UploadFile"];  
  39.                 filedata = Guid.NewGuid() + fname;  
  40.                 fname = Path.Combine(context.Server.MapPath("~/" + uploaddir + "/"), filedata);  
  41.                 file.SaveAs(fname);  
  42.             }  
  43.         }  
  44.         context.Response.ContentType = "text/plain";  
  45.         context.Response.Write("File Uploaded Successfully:" + filedata + "!");  
  46.         //if you want to use file path in aspx.cs page , then assign it in to session  
  47.         context.Session["PathImage"] = filedata;  
  48.     }  
  49.     public bool IsReusable {  
  50.         get {  
  51.             return false;  
  52.         }  
  53.     }  
  54. }  
web.config code
  1. <?xml version="1.0"?>  
  2. <!--  
  3. For more information on how to configure your ASP.NET application, please visit  
  4. http://go.microsoft.com/fwlink/?LinkId=169433  
  5. -->  
  6. <configuration>  
  7.     <system.web>  
  8.         <compilation debug="true" targetFramework="4.0" />  
  9.     </system.web>  
  10.     <appSettings>  
  11.         <add key="Upload" value="UploadFile" />  
  12.     </appSettings>  
  13. </configuration>  
Default.aspx code
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3.     <html xmlns="http://www.w3.org/1999/xhtml">  
  4.   
  5.     <head runat="server">  
  6.         <title></title>  
  7.         <%-- Should have internet connection for loading this file other wise inherit own js file for supporting js library--%>  
  8.             <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>  
  9.             <script type="text/javascript">  
  10.                 function onupload() {  
  11.                     $(function() {  
  12.                         var fileUpload = $('#<%=FileUpload.ClientID%>').get(0);  
  13.                         var files = fileUpload.files;  
  14.                         var test = new FormData();  
  15.                         for (var i = 0; i < files.length; i++) {  
  16.                             test.append(files[i].name, files[i]);  
  17.                         }  
  18.                         $.ajax({  
  19.                             url: "UploadFile.ashx",  
  20.                             type: "POST",  
  21.                             contentType: false,  
  22.                             processData: false,  
  23.                             data: test,  
  24.                             success: function(result) {  
  25.                                 if (result.split(':')[0] = "File Uploaded Successfully") {  
  26.                                     document.getElementById("<%=lbl_smsg.ClientID%>").innerText = result.split(':')[0];  
  27.                                 } else {  
  28.                                     document.getElementById("<%=lbl_emsg.ClientID%>").innerText = result;  
  29.                                 }  
  30.                             },  
  31.                             error: function(err) {  
  32.                                 alert(err.statusText);  
  33.                             }  
  34.                         });  
  35.                     })  
  36.                 }  
  37.             </script>  
  38.     </head>  
  39.   
  40.     <body>  
  41.         <form id="form1" runat="server">  
  42.             <asp:ScriptManager ID="scmain" runat="server"></asp:ScriptManager>  
  43.             <asp:UpdatePanel ID="upmain" runat="server">  
  44.                 <ContentTemplate>  
  45.                     <fieldset>  
  46.                         <legend>Upload File WithOut PostBack inside Update Panel</legend>  
  47.                         <asp:FileUpload ID="FileUpload" runat="server" />  
  48.                         <input type="button" id="btnUpload" value="Upload Files" onclick="onupload();" />  
  49.                         <asp:Label ID="lbl_emsg" runat="server" ForeColor="Red"></asp:Label>  
  50.                         <asp:Label ID="lbl_smsg" runat="server" ForeColor="Green"></asp:Label>  
  51.                     </fieldset>  
  52.                 </ContentTemplate>  
  53.             </asp:UpdatePanel>  
  54.         </form>  
  55.     </body>  
  56.   
  57.     </html>  
Default.aspx code.cs code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. public partial class _Default: System.Web.UI.Page  
  8. {  
  9.     protected void Page_Load(object sender, EventArgs e) {}  
  10. }