Reputation: 115
I am trying to make a feature for my web application that allows the user to upload multiple images as a part of a blog post, then view them later on a page that shows a list of all blog posts. What I am trying to do is, allow the user to upload multiple images and save those images to localStorage. Currently I am looping through all the image files the user has uploaded, then adding a new fileReader to each one. In order to add them to the localStorage, I know I have to make the key value of each image different (i.e. img1=the first image, img2=the second image, etc.) As per the code below, I am changing the key value for each image uploaded using a for loop, and setting it to img${i}
.
However when I try to add a "load" event listener onto each fileReader component to read each individual image file in order to save it onto localStorage, because it is a "load" event the value of the "i" is different. So as a result, I can only save the final image that has been uploaded (i.e. img3). I am assuming this is caused by the code that is within a "load" event so that it will only consider the final "i" value when all the files have loaded. Would there be a way around this issue? Any help towards the right direction is greatly appreciated. I am trying to achieve this in pure javascript so no jquery please. Thank you.
HTML
<!--Upload images-->
<input type="file" id="filetag" multiple accept=".jpg,.jpeg,.png,.gif">
<img id="preview">
Javascript
const fileSelector=document.getElementById('filetag');
const display = document.getElementById("preview");
fileSelector.addEventListener('change',(e)=>{
//gets all the files uploaded
let fileList = e.target.files;
console.log(fileList)
for(i=0;i<fileList.length;i++){
//add a new fileReader for each element
let reader = new FileReader();
reader.addEventListener("load", () =>{
//store each uploaded image into localStorage
localStorage.setItem(`img${i}`,reader.result)
console.log(i)
})
reader.readAsDataURL(fileList[i]);
}
})
Upvotes: 1
Views: 3161
Reputation: 476
First, I don't think that you should use LocalStorage for this. Besides LocalStorage size is limited. In case you have a back-end, those images should be saved in the server, and then just load them with the URL, like any normal website.
In any case, I answer your question. Instead of using an array (and having that problem with the index), turn it into an object and then use the object key:
let fileList = e.target.files;
let files = {};
let index = 0;
for(let file of files) {
files[index] = file;
index ++;
}
// Now iterate object instead of array
Object.keys(files).forEach( key => {
let reader = new FileReader();
reader.addEventListener("load", () =>{
localStorage.setItem(`img${key}`,reader.result)
})
reader.readAsDataURL(files[key]);
});
Upvotes: 1