This is a solution that I use. It handles the upload of multiple images. If you only wish to provide the option to upload one image at a time, then you can simply change the HTML for the input element. For either of these inputs, the javascript I provided runs results in the same execution. Then it becomes a matter of you limiting your file upload to one or many files.
For multiple files: <input type="file" id="files" name="files[]" multiple />
For one single file: <input type="file" id="files" name="file" />
var numDocuments = 0;
var numDocumentsProcessed = 0;
function processFiles() {
numDocuments = files.length;
for (var i = 0, f; f = files[i]; i++) {
var fileReader = new FileReader();
fileReader.onloadend = (function (file) {
return function (evt) {
doSomethingWithFile(evt, file)
}
})(f);
fileReader.readAsDataURL(f);
}
}
function onFilesSelected(event) {
files = event.target.files; // FileList object
processFiles();
}
function doSomethingWithFile(evt, file) {
var key = file.name;
var value = evt.target.result;
var container = document.getElementById('image-container');
var image = document.createElement('img');
image.src = evt.target.result;
container.appendChild(image);
if (++numDocumentsProcessed === numDocuments) {
//final steps after final image processed
}
}
document.getElementById('files').addEventListener('change', onFilesSelected, false);
<input type="file" id="files" name="files[]" multiple />
<br>
<div id="image-container"></div>
console.log(this.files[0]);