Reputation: 61
How to code the array of images in the localstorage?
I cannot make the array of images(base64) into the localstorage. And I want to update back (base64) in input for updating it into the server. Please help me, thank you!
<input type="file" class="file-upload" id="fileUpload">
ready(){
super.ready();
this.$.fileUpload.addEventListener('change', (e) => {
var filesToUpload = this.$.fileUpload;
var files = filesToUpload.files;
var maxFiles = files.length;
var fd = new FormData();
if (FileReader && files && files.length) {
for (var i = 0; i < maxFiles; i++) {
(function(file){
var name = file.name;
var fr = new FileReader();
fr.onload = function(image) {
return function(evt) {
image.src = evt.target.result;
}
var arr = [];
arr.push(fr.result);
if (arr.length == files.length){
console.log(arr);
localStorage.setItem('arr', JSON.stringify(arr));
}
// arr.push(fr.result);
// var arr = JSON.parse(localStorage.getItem('arr')) || [];
// arr = fr.result;
// localStorage.setItem('arr', JSON.stringify(arr));
}
fr.readAsDataURL(file);
})(files[i]);
}
}
});
}
Upvotes: 1
Views: 711
Reputation: 61
I've made it successfully! I like to share it with those who view this.
<input type="file" class="file-upload" id="fileUpload">
<vaadin-button on-tap="submit">Submit</vaadin-button>
submit(e) {
e.preventDefault();
var list = !!localStorage.getItem('imageData') ? JSON.parse(localStorage.getItem('imageData')) : [];
var input = this.$.fileUpload;
var files = input.files;
var reader = new FileReader();
reader.onload = function(e) {
// localStorage["imageData"] = reader.result;
list.push(reader.result);
localStorage["imageData"] = JSON.stringify(list);
};
reader.readAsDataURL(files[0]);
}
Upvotes: 0