Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Multiple file uploads like in Facebook

0.00/5 (No votes)
4 Dec 2013 1  
Multiple file uploads using jQuery without loss of file on multiple add and click.

Introduction

In a project I needed to upload multiple images to the server as Facebook uses on their site where the user uploads images and before posting to the server it shows them as thumbnails.

Background

I only needed some jQuery and JavaScript code. This bunch of code solves many issues like:

  • How to trigger the click event of the file upload control from another element's click.
  • How to show selected images in a div before posting it to the server.
  • When the user clicks many times the previous image should be selected up to when the user finally posts the images to the server.
  • Change event of file upload.

Using the code

How to trigger the click event of the file upload control from another element's click: 

$(document).ready(function () {
$(".sss").on("click", function () {
 $("#fuPuzzleImage").click();
});

How to show the selected images in a div before posting it to the server: 

function readImage(file) {
 var reader = new FileReader();
 var image = new Image();
 reader.readAsDataURL(file);
 reader.onload = function (_file) {
     image.src = _file.target.result;   // url.createObjectURL(file);
     image.onload = function () {
         var w = this.width,
    h = this.height,
    t = file.type,                      // ext only: // file.type.split('/')[1],
    n = file.name,
    s = ~ ~(file.size / 1024) + 'KB';
         $(".f").css("visibility", "visible");
         $('.f .g').append('<img style="max-width:102px; " + 
            "max-height:102px; margin-left:3px;" src="' + this.src + '"> ' + '   ');
        // $('.ms').css("display", "none");
     };
     image.onerror = function () {
         alert('Invalid file type: ' + file.type);
     };
 };
}

Change event of the file upload control:

$("#fuPuzzleImage").change(function (e) {
 if (this.disabled) return alert('File upload not supported!');
 var F = this.files;
 if (F && F[0]) for (var i = 0; i < F.length; i++) readImage(F[i]);
}); 

When the user clicks many times the previous image should be selected up to when the user finally posts the images to the server.

function AddMoreImages() {
     if (!document.getElementById && !document.createElement)
         return false;
     var fileUploadarea = document.getElementById("fileUploadarea");
     if (!fileUploadarea)
         return false;
     var newLine = document.createElement("br");
     fileUploadarea.appendChild(newLine);
     var newFile = document.createElement("input");
     newFile.type = "file";
     newFile.setAttribute("class", "fileUpload");

     if (!AddMoreImages.lastAssignedId)
         AddMoreImages.lastAssignedId = counter;
     newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
     newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
     newFile.setAttribute("multiple", "multiple");
     newFile.setAttribute("style", "display:none");
     var div = document.createElement("div");
     div.appendChild(newFile);
    
     div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
     fileUploadarea.appendChild(div);
     d("#FileUpload" + AddMoreImages.lastAssignedId);
     AddMoreImages.lastAssignedId++;
}

function d(ff) {
 a = ff;
 $(ff).click();
 $(ff).change(function (e) {
     if (this.disabled) return alert('File upload not supported!');
     var F = this.files;
     if (F && F[0]) for (var i = 0; i < F.length; i++) readImage(F[i]);
   
 });
}

Finally, the code-behind from button click:

protected void Button1_Click(object sender, EventArgs e)
{
    try
    {
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++)
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {                        
                hpf.SaveAs(Server.MapPath("~/uploads/") + 
                    System.IO.Path.GetFileName(hpf.FileName));
            }
        }
    }
    catch (Exception)
    {
       throw;
    }
}

.aspx  

<form id="form1" runat="server">

  <div >
     <div class="sss">
  Add +
     </div>

    <div>
    <div id="fileUploadarea"><asp:FileUpload ID="fuPuzzleImage" 
          style="display:none"  multiple="multiple" 
          runat="server"  /><br /></div><br />
    </div>
   
   <div class="f">
   <div class="g">   
   </div>
   </div>
      <asp:Button ID="Button1" runat="server"
          onclick="Button1_Click" Text="Upload" />
    </div>
    </form>

Points of Interest

Using jQuery is always fun. You can learn from this example how to use and generate a dynamic ID.

History

If you see any errors or have recommendations for improvements, then please comment.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here