Previewing Images with jQuery : Data URIs vs Object URLs

javascript
Published on November 27, 2016

It is common for web applications to show a preview of the image to be uploaded, before the user actually uploads it to the server. A local image on the user's computer can be previewed in 2 ways - using the Data URI of the image or by using the Object URL of the image.

Method 1 - Using Data URIs

In this the src attribute of the <image> element is set to the data URI of the image. A data URI basically is the base64 encoded data of the image file. We can get the base64 encoded data of the image by using a FileReader object and reading the image as a data URI through the readAsDataURL() method.

Note that FileReader reads files asynchronously. When the file loading is finished, it sends the base64 encoded data to a callback function.

// $("#file-to-upload") refers to a <input type="file" />
$("#file-to-upload").on('change', function() {
    var reader = new FileReader();
    reader.onload = function(){
        $("#image").attr('src', reader.result).show();
    };
    reader.readAsDataURL($("#file-to-upload").get(0).files[0]);   
});

This is how an image element loaded from a Data URI looks like :

Method 2 - Using Object URLs

In this case the src attribute of the <image> element is set to the Object URL of the image. In simple words Object URL's are URL's that point to files on the user's computer (the entire file is not read into memory). Object URL's are dynamically assigned by the browser. Even if you have created an Object URL for a file, the second time you try creating an Object URL for the same file, you will get a different URL.

This is how an image element loaded from an Object URL looks like :

You can get the Object URL of a file using the createObjectURL() method of the global object URL.

$("#file-to-upload").on('change', function() {
    var image_object_url = URL.createObjectURL($("#file-to-upload").get(0).files[0]);
    $("#image").attr('src', image_object_url).show();
});

Conclusion

If you don't need to read the image file other than just previewing it, using an Object URL is better. It is useless to read the whole the image if you don't need it afterwards. Also the callback function required in FileReader is a useless hindrance in writing simple top-to-bottom executing code.

In this Tutorial