In this tutorial, you will learn how to upload multiple files using JQuery via Generic Handler in ASP.Net c#. We will not use any html form tags. It will be purely based on Javascript and using FormData object to build the file object list. Let's begin with the html code first. We need to write a html upload input that will enable user to select multiple files. We also need to write a div tag that will load a preview of selected files.
<input type="file" multiple="true" id="fUpload" /> <div id="file-list"></div>
The next thing we need to include is the jquery file, we going to use hosted google file as it will be faster to download.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Once the html code is done, we can start build the javascript code. I have included comments to describe further what the code is doing.
<script type="text/javascript"> $(function () { //we apply an event to automatically list of files when the user select the files // the files will be built inside a table that includes the file name, size and the upload status. $("input#fUpload").change(function () { var fileList = ""; if ($(this).prop("files").length > 0) { fileList = "<table class=\"table-upload\" cellpadding=\"0\" cellspacing=\"0\">"; fileList = "<tr class=\"header-row\">"; fileList = "<td class=\"header-filename\">File Name</td>"; fileList = "<td class=\"header-filesize\">Size</td>"; fileList = "<td class=\"header-status\">Status</td>"; fileList = "</tr>"; for (i = 0; i < $(this).prop("files").length; i++ ) { fileList = "<tr id=\"row-file" + i + "\" class=\"row-file\">"; fileList = "<td class=\"row-filename\">" + $(this).prop("files")[i].name "</td>"; fileList = "<td class=\"row-filesize\">" + ($(this).prop("files")[i].size / 1048576).toFixed(2) + " MB</td>"; fileList = "<td id=\"row-status" + i + "\" class=\"row-status\"> </td>"; fileList = "</tr>"; } fileList = "</table>"; } if (fileList.length > 0) { $("#file-list").html(fileList); $("#file-list").slideDown(); } for (i = 0; i < $(this).prop("files").length; i++ ) { uploadImage(i); } }); }); //This will be the function to post image to generic handler //the parameter position will be used to identify which image file is going to be upload function uploadImage(position) { //we include a random number just to make sure it is unique and not cache. var randomnumber = Math.floor(Math.random() * 10001); //we use the FormData object to build the file uploads var form_data = new FormData(); var objFiles = $("input#fUpload").prop("files"); form_data.append("file", objFiles[position]); //we set the status saying the site is currently uploading the file. Note: you can remove the image ajax animated loading if you do not have it and just leave the text information base only. Make sure you set the URL for the generic handler path correctly. $("#row-status" position).html("<img src='ajax-loading.gif'/> Uploading.."); $.ajax({ url: "/uploadhandler.ashx?rdm=" + randomnumber, cache: false, contentType: false, processData: false, data: form_data, type: 'post', success: function (response) { //if the post is success it will go here }, error: function (xhr, ajaxOptions, thrownError) { //if there is an error it will be here //to display an error message you can use xhr.responseText }, complete: function () { //Once the call to generic handler is complete, this will be called. //In this case, we want tell the user that the upload is completed. $("#row-status" position).html("Completed"); } }) } </script>
When we upload multiple files, we want to style the table so it looks good and easy to see. You can touch up the following styles if you prefer.
<style type="text/css"> /**************** FILE UPLOAD *********************/ .table-upload { min-width:350px; border-top:solid 1px #ccc; border-left:solid 1px #ccc; } .table-upload td { padding:5px 10px; border-right:solid 1px #ccc; border-bottom:solid 1px #ccc; } .header-row{ background:#606264; height:30px; line-height:30px; color:#fff; } /**************** END FILE UPLOAD *********************/ </style>
Now the last part, we are going to write a simple generic handler that will accept any posted file. Note: I do not include any restriction of what types of files you can upload. It is up to you to handle this one, it can be any restriction of file types or file sizes. So feel free to play around. See below generic handler code for more details.
<%@ WebHandler Language="C#" Class="UploadHandler" %> using System; using System.Web; using System.IO; public class UploadHandler : IHttpHandler { public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; string pathSave = context.Server.MapPath("/temp"); if (!Directory.Exists(pathSave)) { try { Directory.CreateDirectory(pathSave); } catch { } } for(int i = 0; i < context.Request.Files.Count; i++ ){ HttpPostedFile objHttpPostedFile = (HttpPostedFile)context.Request.Files[i]; objHttpPostedFile.SaveAs(string.Concat(pathSave, "/", objHttpPostedFile.FileName)); } } public bool IsReusable { get { return false; } } }