- In this Demo, “We will upload a image file to browser and preview it without uploading to a server”.
- The steps to preview of an images:-
1. Adding a change Event to “input type file” and listening in a callback function.
2. Initialize the Reader.
3.Attaching “onload” event to reader and in callback change the SRC value.
4. Convert the image file selected ed to data url and load the reader.
- The HTML code :-
Select an Image :
<input id="ts-select-image" type="file" />
<img id="ts-preview-container" />
- The jquery code:-
$('#ts-select-image').on('change',function(e){
var target = e.target,
/*Getiing the selected file*/
imgFile =target.files[0],
readerFile = new FileReader() ;
/*Attaching loading event to the reader*/
readerFile.onload = function(loadEvent){
$('#ts-preview-container').attr('src',loadEvent.target.result)
}
/*Loading the dataurl to reader*/
readerFile.readAsDataURL(imgFile)
})
- Fiddle link for the above demo:-
http://jsfiddle.net/techblogger/GeZhM/1/embedded/result/
- The output will look like below:-