使用FileReader将输入文件数组转换为base64

时间:2020-08-19 16:37:48

标签: javascript html forms filereader fileapi

我有一个允许用户输入多个文件的表格。提交表单后,我将获得用户输入的文件列表,然后将数组中的每个文件转换为base64。我在弄清楚确切如何做最后一部分时遇到了麻烦-将数组中的每个文件转换为base64,然后返回列表。这是我到目前为止的内容:

我编写的代码不起作用,但我认为我在正确的轨道上(使用map函数,FileReader等)

<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>

任何指导表示赞赏!

1 个答案:

答案 0 :(得分:2)

嗨,这是异步操作。尝试将其包装在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
  });
}