Sunday, April 6, 2014

Image upload preview using my JQuery Upload Plugin

Adding a simple image preview during the upload process can be easily done by doing some tweaking to my Upload Plugin demos.

Here is the modified demo: http://danielm.herokuapp.com/demos/dnd/image-preview.php

The magic happens on onNewFile(id, file); our new file callback recives an HTML5 File object as parameter which can be used with the FileReader to accomplish our goal.

The code is very self explanatory:

    onNewFile: function(id, file){

      // Checks if this feature if availabe to the user
      if (typeof FileReader !== "undefined"){
            
        var reader = new FileReader();

        // Our <img> object
        var img = $('your-image-dom-object');

        reader.onload = function (e) {
           img.attr('src', e.target.result);
        }

        reader.readAsDataURL(file);

      }
  }

Modern browsers like Chrome/Firefox or IE10 support this feature; which is enough since those are also my uploader plugin requirements.