Rudolph Savoy
Rudolph Savoy

Reputation: 91

JavaScript Async readAsDataURL multiple files

I have a list of files I need to save and in addition to the name I need to send the readAsDataURL to the server as well.

The problem is I am not sure how to do it with the async nature of readAsDataURL. Because to save the DATAURL to the array I need to look up the name of the file which is in the files list. and I cannot pass the file to the async method of readAsDataURL. How do you write this properly to work? The end result is I want a list of files sent to the server in one JSZip file.

function saveFileList(files)
{
    for (var i = 0, file; file = files[i]; i++) {

        var fr = new FileReader();
        fr.onload = function(e){
        if (e.target.readyState == FileReader.DONE) {
            var tt = e.target.result.split(",")[1];
                             //update the record in the list with the result
            }
         };

        var pp = fr.readAsDataURL(file);
  }

Upvotes: 9

Views: 11601

Answers (3)

Andrii Kudriavtsev
Andrii Kudriavtsev

Reputation: 1304

If you have FileList and you need to get array of base64 string, you need do this

export async function fileListToBase64(fileList) {
  // create function which return resolved promise
  // with data:base64 string
  function getBase64(file) {
    const reader = new FileReader()
    return new Promise(resolve => {
      reader.onload = ev => {
        resolve(ev.target.result)
      }
      reader.readAsDataURL(file)
    })
  }
  // here will be array of promisified functions
  const promises = []

  // loop through fileList with for loop
  for (let i = 0; i < fileList.length; i++) {
    promises.push(getBase64(fileList[i]))
  }

  // array with base64 strings
  return await Promise.all(promises)
}

use it like this

const arrayOfBase64 = await fileListToBase64(yourFileList)

Upvotes: 14

P.M
P.M

Reputation: 3158

An alternative to Russell G's answer:

var reader = new FileReader();
reader.onload = function(event){
   payload = event.target.result;
   var filename = file.name, filetype = file.type;//etc
   //trigger a custom event or execute a callback here to send your data to server.
};
reader.onerror = function(event){
   //handle any error in here.
};
reader.readAsDataURL(file);

Upvotes: 0

Russell G
Russell G

Reputation: 478

You need another function around it, so you can pass the file in. Try this:

var reader = new FileReader();

reader.onload = (function(theFile) {
   return function(e) {
      if(reader.readyState == FileReader.DONE)
         alert(theFile.name);   // The file that was passed in.
      }
   };
})(file);

reader.readAsDataURL(file);

Upvotes: 0

Related Questions