JS get multiple files from upload

I'm trying to show multiple files that are uploaded however my console log of preview is blank. What am I missing here?

function readURL(input) {
            var preview = '';
            if (input.files && input.files[0]) {
                $(input.files).each(function (index) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        preview += '<div class="image">';
                        preview += '<img src="' + e.target.result + '">';
                        preview += '</div>';
                    }
                    reader.readAsDataURL(input.files[index]);
                });
                console.log(preview);
                $('.preview').html(preview);
            }
        }

        $("#logos").change(function () {
            readURL(this);
        });

1 answer

  • answered 2018-10-11 19:59 jered

    The value of preview is still '' when you log it to the console. This is because the FileReader "load" action is asynchronous, hence why you have to attach an onload handler to it. Try putting the console.log inside of the onload function.

            if (input.files && input.files[0]) {
                $(input.files).each(function (index) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        preview += '<div class="image">';
                        preview += '<img src="' + e.target.result + '">';
                        preview += '</div>';
                        console.log(preview);
                        $('.preview').html(preview);
                    }
                    reader.readAsDataURL(input.files[index]);
                });
            }
    

    In other words, the onload function doesn't trigger until some arbitrary time after you do reader.readAsDataURL(input.files[index]).