Here this article explains how to preview an image before uploading on thr server side in jQuery
Using HTML 5 FileReader() we can able to preview the image before uploading it in jQuery.
With jQuery
Step 1 HTML Markup
Lets set up the environment to upload image and preview image.
Here we have added a input file tag and a div. this div tag is used as holder for image ie. preview image before uploading to server.
Step 2 jQuery Code
Before writing code we need to add a jQuery library file
Next here we bind a change event to our input file tag, and then will check for browser support HTML5 FileReader method, if not then we throw an error.
Without jQuery
Step 1 HTML Markup
As we have done earlier, the first we setup environment to upload and preview image. Here am adding one < input > tag with file as type and one image (< img >) tag to preview selected image.
Step 2 javascript code
In this javascript code I used 6 steps
- initializing the fileTag variable with ids
- checking for non empty fileTag variable
- calling the function if there is a change in fileTag
- checking for the presence of file
- declaring object for
FileReader() - setting the attribute
src
var fileTag = document.getElementById("photo"),
preview = document.getElementById("previewHolder");
if(fileTag){
fileTag.addEventListener("change", function() {
changeImage(this);
});
}
function changeImage(input) {
var reader;
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function(e) {
preview.setAttribute('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
see Multiple image previews before uploading to server
