Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@maximishchenko
Last active August 14, 2016 11:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximishchenko/e1f9e1f92da44ce0459218ee3464c520 to your computer and use it in GitHub Desktop.
Save maximishchenko/e1f9e1f92da44ce0459218ee3464c520 to your computer and use it in GitHub Desktop.
JavaScript Preview Image Before Upload
<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