Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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". In firefox, however, it works fine.

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)
like image 703
user467526 Avatar asked Apr 24 '13 01:04

user467526


2 Answers

Unfortunately doesn't work. As mentioned by janje you will need to create a new FileReader per iteration. Also remember to create a closure when binding the event handler, due to the "creating functions in a loop" problem in JavaScript.

Eric Bidelman's post is a rather good source:

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);
    }
  }
like image 119
Noel Abrahams Avatar answered Oct 23 '22 19:10

Noel Abrahams


You have to create a new FileReader (and a new variable to store it in) for every iteration using readAsDataURL.

like image 27
pishpish Avatar answered Oct 23 '22 20:10

pishpish