ASP.NET AJAX File Upload

jQuery can help in uploading a file on asp.net web page asynchronously. Add a generic handler in asp.net project like below.

Upload Generic Handler – Code behind file (upload.ashx)


public class upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string fileName = HttpContext.Current.Request.QueryString["FileName"].ToString();
            using (FileStream fs = File.Create("[Path]\\" + fileName))
            {
                Byte[] buffer = new Byte[32 * 1024];
                int read = context.Request.InputStream.Read(buffer, 0, buffer.Length);
                while (read > 0)
                {
                    fs.Write(buffer, 0, read);
                    read = context.Request.InputStream.Read(buffer, 0, buffer.Length);
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

ASPX Code


<form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fuAttachment" runat="server" /> 
        <asp:Button ID="btnUpload" OnClientClick="return false;" Text="Upload File" runat="server" />
    </div>
    <div id="progress">
    </div>
    </form>
    
    <script type="text/javascript">

	    var currFile = 0;
	    var totalFileCount = 0;
	    function sendFile(file) {
	        debugger;
	        $.ajax({
	            url: 'upload.ashx?FileName=' + file.name, // send as many parameters to process at server side
	            type: 'POST',
	            xhr: function() {
	                myXhr = $.ajaxSettings.xhr();
	                if (myXhr.upload) {
	                    myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
	                }
	                return myXhr;
	            },
	            success: function(result) {
	                alert('uploaded!');
	            },
	            error: function(result) {
	                alert('error!');
	            },
	            data: file,
	            cache: false,
	            contentType: false,
	            processData: false
	        });
	        
	        function progressHandlingFunction(e) {
	            if (e.lengthComputable) {
	                var s = parseInt((e.loaded / e.total) * 100);
	                $("#progress").text(s + "%");	                
	            }
	        }
	    }

	    function uploadFile() {	        	        
	        sendFile($("#<%= fuAttachment.ClientID %>")[0].files[0]);
	    }

	    $(document).ready(function() {
	        $('#<%= btnUpload.ClientID %>').click(function() {
	            if ($("#<%= fuAttachment.ClientID %>")[0].files[0] == null) {
	                alert('please select file');
	            } else {
	                uploadFile();
	            }
	        });
	    });

	</script>

Leave a Reply

Your email address will not be published.