最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Failed to execute 'readAsDataURL' on 'FileReader': the object is already busy readi

programmeradmin3浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 14

you 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)
        }
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论