Sami Junior
Sami Junior

Reputation: 135

Convert array of inputted files to base64 using FileReader

I have a form which allows the user to input multiple files. Once the form is submitted, I get the list of files that the user inputted and then convert each file in the array to base64. I'm having trouble figuring out exactly how to do the last part - convert each file in the array to base64, then returning the list. Here's what I have so far:

The code I've written doesn't work but I think I'm on the right track (using the map function, FileReader etc.)

<form id="sendEmailForm" onsubmit="handleFormSubmit(this)">

    <div class="custom-file">
        <input type="file" class="custom-file-input" id="images_input" name="images_input" multiple required>
        <label class="custom-file-label" for="images_input">Select images...</label>
    </div>

    <button type="submit">Submit</button>

</form>

<script>
    function handleFormSubmit(formObject) {
        // Get array of inputted images
        var images = formObject.images_input.files;
        
        // Somehow (?) iterate over images and return the base64 content of each image
        var base64Images = images.map(function (image) => {
            const fileReader = new FileReader();

            var base64Image = fileReader.onload = (image) => {
                return file.target.result.split(",")[1];
            };

            fileReader.readAsDataURL(image);
            return base64Image;
        });

        // Send base64Images to server
    }
</script>

Any guidance is appreciated!

Upvotes: 3

Views: 1109

Answers (1)

mpstv
mpstv

Reputation: 101

Hi this is an asynchronous operation. Try to wrap this in Promise:

function handleFormSubmit(formObject) {
  // Get array of inputted images
  const images = formObject.images_input.files;

  Promise.all(
    images.map(
      (image) =>
        new Promise((resolve, reject) => {
          const fileReader = new FileReader();

          fileReader.onload = (file) => {
            resolve(file.target.result.split(',')[1]);
          };

          fileReader.onerror = (error) => reject(error);

          fileReader.readAsDataURL(image);
        })
    )
  ).then((base64Images) => {
    // Send base64Images to server
  });
}

Upvotes: 4

Related Questions