Champer Wu
Champer Wu

Reputation: 1271

base64 image file in array is undefined in javascript

I tried to load the base64 image string into array by <input type="file"/> I am sure the string is in the array but when I call the array element the console callback is undefined.

as following my code:

fileChange(event){
    if (event.target.files && event.target.files[0]) {
            let imageFiles = [];
            for (var i = 0; i < event.target.files.length; i++) {

              let reader = new FileReader();
              reader.readAsDataURL(event.target.files[i]);
              reader.onload = (e) => {
                  imageFiles[i] = e.target.result;
                  console.log(e.target.result);
              };
            }
            console.log(imageFiles);
            console.log(imageFiles[0]);
        }
  }

//console result:
//"base64 string"
//[]-> 0: "base64 string"
//undefined

I think it because the base64 string is too long, but I have no idea to solve the problem.

It's some ways to solve it?

Upvotes: 1

Views: 1356

Answers (1)

Kirill Simonov
Kirill Simonov

Reputation: 8491

These two statements

console.log(imageFiles);
console.log(imageFiles[0]);

are called immediately, when reader.onload is not completed yet. Hence, the imageFiles array is empty.

You need to wait until the image is loaded to be able to log it. One way is to use Promises. Here is an example of loading multiple files. Promise.all will wait until all files are loaded and then log them.

document.getElementById("file").addEventListener("change", fileChange);
function fileChange(event) {
    if (event.target.files && event.target.files[0]) {
        console.clear();
        console.log("Loading selected files...");
        let promises = [];
        for (var i = 0; i < event.target.files.length; i++) {
            promises[i] = new Promise(resolve => {
                let reader = new FileReader();
                reader.readAsDataURL(event.target.files[i]);
                reader.onload = (e) => {
                    resolve(e.target.result);
                };
            });
        }      
        Promise.all(promises).then(console.log);
    }
}
<input type="file" id="file" multiple="multiple"/>

Upvotes: 1

Related Questions