RochCass: Preview Image from File Upload using JavaScript

Demo:

Select Images to Upload:

Steps:

Step 1: Add a input type="file", give it an id and add the attribute multiple to allow for multiple file upload

<input type="file" id="files" name="files" multiple >

Step 2: On Page load, add an event listener for your input file upload change event

<script>
window.onload = function() {
var inputLocalFont = document.getElementById("files");
inputLocalFont.addEventListener("change", previewImages, false);
}
</script>


Step 3: Create a previewImages() function to be called when the change event is fired

<script>
//Preview new images to upload
function previewImages() {
var fileList = this.files;
var previewImages = document.getElementById("previewImages");

var anyWindow = window.URL || window.webkitURL;

previewImages.innerHTML = "";

for (var i = 0; i < fileList.length; i++) {
var objectUrl = anyWindow.createObjectURL(fileList[i]);
var filenameExt = fileList[i].name.split('.png');
var filename = filenameExt[0];
var holder = '<div style="float:left;">' +
' <img alt="" src="' + objectUrl + '" width="100px" height="100px" style="margin: 15px;" />' +
'</div>';

previewImages.innerHTML += holder;

window.URL.revokeObjectURL(fileList[i]);

}

//This will be used to set the hight of the parent div
previewImages.innerHTML += "<div style='width: 100%; clear: both; float: none'></div>";
} </script>


Goodluck :)

Back to Article