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)
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);
}
}
You have to create a new FileReader (and a new variable to store it in) for every iteration using readAsDataURL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With