FileReader不会从多个文件渲染图像 [英] FileReader does not render the image from multiple files

查看:57
本文介绍了FileReader不会从多个文件渲染图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个多类型文件输入,然后在对输入文件触发onChange事件时,它将循环遍历每个文件,然后创建一个FileReader(),然后将每个文件渲染为图像,但似乎只渲染第一个一个而不是每个文件,有什么想法,请帮忙吗?

I have this multiple type file input and then when onChange event is triggered unto the input file then it will loop through each file and then create a FileReader() and then render each file to an image but seems it only render the first one and not each file, any ideas, help please?

document.querySelector("input")
    .onchange = function(e) {
      for (var i = 0; i < e.target.files.length; i++) {
        var img = document.createElement("img");

        var reader = new FileReader();
        reader.onload = function (e) {
            img.src = e.target.result;
            document.body.appendChild(img);
        }
        reader.readAsDataURL(e.target.files[i]);
      }
    }

img{
width:50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" multiple><br><br><br>

推荐答案

FileReader异步返回结果.您可以创建一个闭包以在for循环内使用以处理每个文件.

FileReader returns results asynchronously. You can create a closure to use within for loop to process each file.

document.querySelector("input")
  .onchange = function(e) {
    for (var i = 0; i < e.target.files.length; i++) {
      // use IIFE as a closure
      (function(file) {
        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onload = function(e) {
          img.src = e.target.result;
          document.body.appendChild(img);
        }
        reader.readAsDataURL(file);
      })(e.target.files[i]); // pass current File to closure 
    }
  }

img {
  width: 50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="file" multiple><br><br><br>

这篇关于FileReader不会从多个文件渲染图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆