简体   繁体   English

使用FileReader时,chrome中的状态错误无效

[英]Invalid state error in chrome when using FileReader

I'm simply trying to use FileReader to display image files, however when I try to use more than 1 image, I get the following "InvalidStateError: DOM Exception 11". 我只是尝试使用FileReader来显示图像文件,但是当我尝试使用多个图像时,我得到以下“InvalidStateError:DOM Exception 11”。 In firefox, however, it works fine. 然而,在Firefox中,它工作正常。

Here's my code 这是我的代码

    function addImages(images)
            {
                var reader=new FileReader()

                reader.onload=function()
                {
                    $("#images").append('<img src="'+this.result+'"/><br/>')
                }

                for(var count=0;count<images.length;count++)
                {
                    reader.readAsDataURL(images[count])
                }
            }

            function uploadImagesToBrowser(e)
            {
                addImages(e.target.files)   
            }
$("#imagefiles").on("change",uploadImagesToBrowser)

Unfortunately doesn't work. 不幸的是不起作用。 As mentioned by janje you will need to create a new FileReader per iteration. 正如janje所提到的,每次迭代都需要创建一个新的FileReader。 Also remember to create a closure when binding the event handler, due to the " creating functions in a loop " problem in JavaScript. 还记得在绑定事件处理程序时创建一个闭包,因为JavaScript 中的 “在循环中创建函数 ”问题。

Eric Bidelman's post is a rather good source: Eric Bidelman的帖子是一个相当不错的来源:

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {

      var reader = new FileReader();

      // Closure to capture the file information.
      reader.onload = (function(theFile) {
        return function(e) {
          // Render thumbnail.
        };
      })(f);

      // Read in the image file as a data URL.
      reader.readAsDataURL(f);
    }
  }

您必须使用readAsDataURL为每次迭代创建一个新的FileReader(以及一个用于存储它的新变量)。

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

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