Last active
August 14, 2016 11:15
-
-
Save maximishchenko/e1f9e1f92da44ce0459218ee3464c520 to your computer and use it in GitHub Desktop.
JavaScript Preview Image Before Upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script type="text/javascript"> | |
/** | |
* Display image selected in html input widget | |
* @param {string} inputID id of html image input | |
* @param {string} imgFieldID id of html img tag | |
* @return none | |
*/ | |
function previewImageBeforeUpload(inputID, imgFieldID) { | |
document.getElementById(inputID).onchange = function () { | |
/** | |
* [reader description] | |
* @type {FileReader} | |
*/ | |
var reader = new FileReader(); | |
/** | |
* [onload description] | |
* @param {[type]} e [description] | |
* @return {[type]} [description] | |
*/ | |
reader.onload = function (e) { | |
/** | |
* id of image | |
* @type {string} | |
*/ | |
var img = document.getElementById(imgFieldID); | |
/** | |
* set Bootstrap class to image input | |
* @type {String} | |
*/ | |
img.className = "img-thumbnail" | |
/** | |
* get loaded data and render thumbnail. | |
* @type none | |
*/ | |
img.src = e.target.result; | |
}; | |
/** | |
* read the image file as a data URL. | |
*/ | |
reader.readAsDataURL(this.files[0]); | |
}; | |
}; | |
</script> | |
<input type="file" id="files" /> | |
<img id="image" /> | |
<script type="text/javascript"> | |
/** | |
* Run function with id's of fileInput and image as arguments | |
*/ | |
previewImageBeforeUpload("files", "image") | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment