Click here to Skip to main content
15,890,882 members
Articles / Programming Languages / Javascript
Tip/Trick

Multiple file uploads like in Facebook

Rate me:
Please Sign up or sign in to vote.
3.00/5 (3 votes)
4 Dec 2013CPOL1 min read 20.9K   2   9   4
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: 

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

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

JavaScript
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:

JavaScript
$("#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.

JavaScript
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:

C#
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  

ASP.NET
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionClarification Pin
EBalaji5-Mar-14 18:26
EBalaji5-Mar-14 18:26 
GeneralMy vote of 1 Pin
Adam R Harris2-Dec-13 6:15
Adam R Harris2-Dec-13 6:15 
Question[My vote of 1] My Vote of 1 Pin
Adam R Harris2-Dec-13 6:14
Adam R Harris2-Dec-13 6:14 
AnswerRe: [My vote of 1] My Vote of 1 Pin
cyber_addicted2-Dec-13 6:24
cyber_addicted2-Dec-13 6:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.