简体   繁体   English

Filereader:多个文件输入仅以一张图像作为预览结束

[英]Filereader: Multiple file input ends with only one image as preview

Trying to figure out how to input multiple files at once and arrange them to divs. 试图弄清楚如何一次输入多个文件并将它们排列到div中。 In result, only the last image of the array appears. 结果,仅出现阵列的最后一个图像。

HTML: HTML:

<input type="file" id="imageinput" accept="image/*" onchange="handleFiles(files)" multiple>
    <div class="cube-layout-1">
        <div id="preview1"></div>
        <div id="preview2"></div>
        <div id="preview3"></div>
        <div id="preview4"></div>
        <div id="preview5"></div>
        <div id="preview6"></div>
    </div>

Javascript: Javascript:

        var j=0;

        function counter() {
            j++;
            return j;
        }

        function handleFiles(files) {
            for (var i = 0; i < files.length; i++) {
                var file = files[i];
                var count = counter();
                var preview = document.getElementById("preview"+count);

                var reader = new FileReader();
                reader.onload =  (function (preview) {
                    return function () {
                        preview.style.backgroundImage = "url(" + reader.result + ")";
                    }
                })(preview);
                reader.readAsDataURL(file);
            }
        }

For example, if I choose 3 images at once, the first two divs get an empty background image and only the last div gets the image. 例如,如果我一次选择3张图像,则前两个div将获得一个空的背景图像,而只有最后一个div将获得该图像。 I know it has something to do with the reader.onload event, which triggers only when the loop ends....but how can I achieve what I am aiming for? 我知道它与reader.onload事件有关,后者仅在循环结束时才触发....但是我如何实现我的目标? Thanks in advance! 提前致谢!

Check out my code try using it, I solved the Async issue, as I needed to add file name along with the preview. 看看我的代码尝试使用它,我解决了异步问题,因为我需要在预览中添加文件名。

  function readURL(input) {
        var file = document.getElementById("article_file").value;
        console.log(file);
        var originalname = file.replace(/C:\\fakepath\\/i, '');
        console.log(name);
        if (DST()) {
            // Daylight Savings, EDT is UTC-4
            var offset = "-4";
        } else {
            // Not Daylight Savings, EST is UTC-5
            var offset = "-5";
        }
        var today = calcTime(offset);

        var month = today.getMonth() + 1;

        // appends 0 to monthes under 10
        if (month < 10)
            month = "0" + month.toString();

        if ($('table.appendo.image-uploader tbody tr').length > 2)
            $('table.appendo.image-uploader tbody tr').each(function (i, ele) {
                if(i==1)
                {
                     $('#image-preview-path').attr('src','src="/images/tp.gif"');
                     $('#image-path').attr('value','');
                }
                else if (i > 1)
                {
                    $(ele).remove();
                }
            });
        $('.upload-article').attr('name', 'Filedata[]');

        var files = $('#article_file')[0].files;
        var name = [];
        var extension = ['.jpg','jpeg','.gif','.png'];
        var flag = 1;
        name['invalid'] = 'invalid';
        for (var z = 0; z < files.length; z++){
            var ext = (files[z].name.substr(-4)).toLowerCase();
            if($.inArray(ext, extension) != -1){

            } else {
                flag = 2;
            }
        }
        var count = files.length;
        if(count <= '6') {
        if(flag == 1) {
        for (var x = 0; x < files.length; x++)
        {

            if (x == 0) {
                var file = files[x];
                var hello = file['name'].replace(/\s/g, '');
                var file_name = hello.replace(/[^.a-z0-9_-\s]/gi, '').replace(/[_\s]_/g, '-');
                name[file['size']] = file_name;
                console.log(files[x]);
                var reader = new FileReader();
                reader.addEventListener('load', function (e) {
                    console.log(e)

                    $('#image-preview-path').attr('src', e.target.result);
                    $('#image-path').attr('value', "/images/uploads/" + today.getFullYear() + "/" + month + "/" + today.getDate() + "/" + name[e.total]);

                });
                reader.onerror = function (event) {
                    console.error("File could not be read! Code " + event.target.error.code);
                };
                reader.readAsDataURL(file);
            } else {
                var file = files[x];
                var hello = file['name'].replace(/\s/g, '');
                var file_name = hello.replace(/[^.a-z0-9_-\s]/gi, '').replace(/[_\s]_/g, '-');
                name[file['size']] = file_name;
                console.log(files[x]);
                var reader = new FileReader();
                reader.addEventListener('load', function (e) {
                    console.log(e)
                    if ($('table.appendo>tbody:eq(0)>tr').length - 1 > 0)
                        index = $('table.appendo>tbody:eq(0)>tr').length - 1
                    else
                        index = 'invalid';
                    var table = $('table.appendo tbody tr:eq(1)').clone();
                    table.find('img').attr('id', 'image-preview-path');
                    table.find('img').attr('src', e.target.result);
                    table.find('input').attr('id', 'image-path');
                    table.find('input').attr('value', "/images/uploads/" + today.getFullYear() + "/" + month + "/" + today.getDate() + "/" + name[e.total]);
                    $('table.appendo.image-uploader tbody').append(table);

                });
                reader.onerror = function (event) {
                    console.error("File could not be read! Code " + event.target.error.code);

                };
                reader.readAsDataURL(file);
            }
        }
      } else {
          alert('Not a valid file extension.');
          $('#article_file').val("");
        } 
      } else {
          alert('You have attempted to queue too many files.\nYou may select six file.');
          $('#article_file').val("");
      }
    }

Got the solution insted of: 得到了以下解决方案:

return function () { preview.style.backgroundImage = "url(" + reader.result + ")";}

it should be: 它应该是:

return function (e) { preview.style.backgroundImage = "url(" + e.target.result + ")";}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM