Custom Templates with jQuery File Upload

Recently I was working on a project which was using the jQuery File Upload Plugin to do multiple file uploads. I needed to show the progress of each upload (in this case just images). Looking through their documentation it shows how to a few ways to do custom templates. By default it uses the Javascript Templates Engine for all of its templating. I wanted to use just a div on the page for my template. Here’s how I ended up doing it.

First My basic markup for the html:

<input type="file" id="fileUploads" name="file" multiple />
<div id="uploadContainer">
 <div class="uploadedImage">
  <img src="myimg.png">
 </div>
 <span id="newImages"></span>
</div>

<div id="template">
 <div class="uploadedImage">
  <img src="" />
  <div class="progressbar"><span class="bar"></span></div>
 </div>
</div>

Basically my “#template” div was a hidden div on the page which I used as the photo being uploaded. Now for the javascript:

var progressElements = { };

$(document).ready( function(){
	
    $("#fileUploads").fileupload({
      dataType: 'json',
      done: function(e, data){
    	    
          var fileName = data.files[0].name;          
          var el = progressElements[ data.files[0].name ];        
          el.find("img:first").attr("src", data.result.thumbnail);
          el.find(".progressbar").hide();
      },
      progress: function(e, data){
    	    var el = progressElements[ data.files[0].name ];
    	    var progress = parseInt(data.loaded / data.total * 100, 10);
    	    el.find(".bar").css('width',progress+"%" );
      },
      add: function(e, data){

   	  var template = $("#reviewTemplate").html();    	       	 
    	  $("#newImages").before(template);

    	  progressElements[ data.files[0].name ] = $("#uploadContainer .uploadedImage:last");
    	  
    	  $("#fileUploads").fileupload("send", {files: data.files});
      },
      autoUpload: true,
      url: 'myUploadUrl',
    });

});

It ended up being pretty simple and self explanatory. The ‘progress’ function is called each time there is a progress update. You can do more advanced templates using their templating engine, however as I was adapting the code to an existing layout and was on a time constraint this was the route I took.

Hope this saves you sometime if you are looking to just quickly add a progress template for the uploaded images.