JavaScript Async readAsDataURL multiple files

file, html, javascript

Solution

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)

Problem

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); } ```

Original source