All of us might be tried to load preview of an image which is to be uploaded to the server. Previously we can’t do this without uploading that particular file to the server. Now the latest versions of most of the browsers supports FILEREADER Web API. Using this we can display the preview of an image file without uploading to the server, using Javascript. The Javascript code given below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //To reduce memory usage when using file reader var blobURL = window.URL || window.webkitURL; function readImgURL(input, imgTagName) { if (typeof FileReader !== "undefined"){ console.log('File Reader suppported...'); //if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { /*$('#'+ imgTagName).attr('src', e.target.result); This method consumes browser local storage heavily */ $('#'+ imgTagName).attr('src', (blobURL.createObjectURL(input))); } reader.readAsDataURL(input); //} } else{ console.log('File Reader not suppported...'); $('#'+ imgTagName).attr('src', 'http://www.sample.com/images/no-image-icon.jpg'); } } |