Preview an image before uploading
This tutorial uses Filereader object to display the images that the user selected. Filereader object lets web application asynchronously read the content of the files stored on the local computer.
To preview an image, we need some space to display the image and a input to select the image. Let’s define a img tag with id preview and an input tag of type file with id imageFile.
1
2
<img src="" id="preview" alt="Preview" height=200px width=500px/><br/>
<input type="file" id="imageFile" onChange="previewImage();"/>
Whenever the content of input tag changes it calls the javascript function previewImage. This function displays the image that the user selected.
The previewImage function is defined as follow:
1
2
3
4
5
6
7
8
9
function previewImage() {
var imageFile=document.getElementById("imageFile");
var file=imageFile.files[0];
var reader=new FileReader();
reader.onload=function(e) {
document.getElementById("preview").src=e.target.result;
}
reader.readAsDataURL(file);
}
This function works as follow: it takes reference to the input element. Define a new Filereader object. Using this object and method readAsDataURL read the content of the file. We define a event handler using Filereader.onload property. This event handler is executed when the load event is fired, when content read with readAsDataURL is available. This event handler set the src attribute of img tag.