Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 277
Sami Junior Avatar asked Sep 05 '26 17:09

Sami Junior


1 Answers

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

like image 135
mpstv Avatar answered Sep 07 '26 06:09

mpstv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!