I want to upload multiple images. When I choose multiple images photoSelected function is called. I want to use base64 but it shows this error on console.
PhotoSelected (e){
Let files = e.target.files;
Let reader = new FileReader();
Let file;
For (let i=0; I<files.length ; i++){
file = files [i];
reader.onload = (file) => {
This.product.photo[i] = reader.result;
}
reader.readAsDataURL(file)
}
}
I want to upload multiple images. When I choose multiple images photoSelected function is called. I want to use base64 but it shows this error on console.
PhotoSelected (e){
Let files = e.target.files;
Let reader = new FileReader();
Let file;
For (let i=0; I<files.length ; i++){
file = files [i];
reader.onload = (file) => {
This.product.photo[i] = reader.result;
}
reader.readAsDataURL(file)
}
}
Share
Improve this question
edited Jun 17, 2019 at 19:08
oshell
9,1231 gold badge30 silver badges50 bronze badges
asked Jun 17, 2019 at 18:27
M R BehruzM R Behruz
571 gold badge1 silver badge5 bronze badges
2
- What was the error? – SolutionMill Commented Jun 17, 2019 at 19:30
- I would just have uploaded all files with formData if i where you instead of using base64 – Endless Commented Jun 18, 2019 at 13:54
1 Answer
Reset to default 14you defined the reader outside the for loop and use the same reader within the loop. this results in the reader being busy. You can solve this by creating one reader for each loop in its own scope, using an IIFE.
PhotoSelected (e){
let files = e.target.files;
let reader = new FileReader();
let file;
for (let i=0; I<files.length ; i++){
(function(file) {
var reader = new FileReader();
reader.onload = (file) => {
this.product.photo[i] = reader.result;
}
reader.readAsDataURL(file)
})(files[i]);
}
}
Since you are using let
already and it uses block scope, you could also create a reader each loop using let
.
PhotoSelected (e){
let files = e.target.files;
let file;
for (let i=0; I<files.length ; i++){
let reader = new FileReader();
file = files [i];
reader.onload = (file) => {
this.product.photo[i] = reader.result;
}
reader.readAsDataURL(file)
}
}