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.
- <Triggers>
- <asp:PostBackTrigger ControlID=""/>
- </Triggers>
UploadFile.ashx Code
- using System;
- using System.Web;
- using System.IO;
- using System.Web.SessionState;
- public class UploadFile: IHttpHandler, IRequiresSessionState {
- public void ProcessRequest(HttpContext context) {
- string filedata = string.Empty;
- if (context.Request.Files.Count > 0) {
- HttpFileCollection files = context.Request.Files;
- for (int i = 0; i < files.Count; i++) {
- HttpPostedFile file = files[i];
- if (Path.GetExtension(file.FileName).ToLower() != ".jpg" &&
- Path.GetExtension(file.FileName).ToLower() != ".png" &&
- Path.GetExtension(file.FileName).ToLower() != ".gif" &&
- Path.GetExtension(file.FileName).ToLower() != ".jpeg" &&
- Path.GetExtension(file.FileName).ToLower() != ".pdf"
- ) {
- context.Response.ContentType = "text/plain";
- context.Response.Write("Only jpg, png , gif, .jpeg, .pdf are allowed.!");
- return;
- }
- decimal size = Math.Round(((decimal) file.ContentLength / (decimal) 1024), 2);
- if (size > 2048) {
- context.Response.ContentType = "text/plain";
- context.Response.Write("File size should not exceed 2 MB.!");
- return;
- }
- string fname;
- if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER") {
- string[] testfiles = file.FileName.Split(new char[] {
- '\\'
- });
- fname = testfiles[testfiles.Length - 1];
- } else {
- fname = file.FileName;
- }
- //here UploadFile is define my folder name , where files will be store.
- string uploaddir = System.Configuration.ConfigurationManager.AppSettings["UploadFile"];
- filedata = Guid.NewGuid() + fname;
- fname = Path.Combine(context.Server.MapPath("~/" + uploaddir + "/"), filedata);
- file.SaveAs(fname);
- }
- }
- context.Response.ContentType = "text/plain";
- context.Response.Write("File Uploaded Successfully:" + filedata + "!");
- //if you want to use file path in aspx.cs page , then assign it in to session
- context.Session["PathImage"] = filedata;
- }
- public bool IsReusable {
- get {
- return false;
- }
- }
- }


Jacky ZhangPosted Aug 27, 2019, 1:33 AM
Can we show priview all selected item before upload it?
Pradeep SahooPosted Nov 8, 2016, 7:40 AM
Nice blog . I was doing the same stuff in one of my requirement . Thanks