JavaScript / jQuery / PHP / Programmings / Technologies

Image preview before upload file

We can preview the uploaded image easily with jQuery or JavaScript before actual upload of file.

Just Follow these Steps

HTML Code

<form id="Imgfrm">
   <input id="imgfile" type="file" /> 
   <img id="preview" src="#" alt="your image" /><
/form>

Then use following jQuery Code (You can use pure JavaScript also)

$("#imgfile").change(function(){
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#preview').attr('src', e.target.result);
        }
        reader.readAsDataURL(this.files[0]);
    }
});

With pure javascript

<form id="Imgfrm">
   <input id="imgfile" type="file" onchange="readURL(this)"; /> 
   <img id="preview" src="#" alt="your image" /><
/form>

Then use following JS Code

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            document.getElementById('preview').src=e.target.result;
        }
        reader.readAsDataURL(input.files[0]);
    }
}

Advertisements

9 thoughts on “Image preview before upload file

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s