Web Snippet: Generate preview from file upload

Html:

<input type="file" id="file" multiple>
<div id="container"></div>

JS:

var app = {};
var container = app.container = document.getElementById('container');
var f = app.file = document.getElementById('file'); // jQuery alternative: $('#file')[0].files[0];
app.file.addEventListener('change', function(){ // jQuery alternative: $('#file').on('change', function(event){
    container.innerHtml = '';
    var len =f.files.length;

    if (len) {
        for (var i = 0; i< len; i++) {
            var file = f.files[i];
            var d = new FileReader();
            d.onload = function(e){
                console.log('On load fired');
                console.log(e);
                console.log(e.currentTarget.result);
                // document.getElementById('img').src = e.currentTarget.result;
                var img = document.createElement('img');
                img.style="max-width: 100vh;"
                container.append(img);
                img.src = e.currentTarget.result
            }
            d.readAsDataURL(f.files[i])

        }
    }
});

 

Leave a Reply

Close Menu