likes
comments
collection
share

【html + 原生js】input标签上传多张图片后如何转成base64数据并返回

作者站长头像
站长
· 阅读数 45

前景摘要,最近帮后端同事解决了一个问题,他需要取到多选图片上传后的每个图片的base64数据。

话不多说,直接上代码吧!

页面部分(页面需要引入jq方可正常运行)

  <input type="file" multiple="multiple" id="imageButton" accept="image/png, image/bmp, image/jpg, image/jpeg"
        class="image-local-input">
    <div id="test">test</div>

逻辑部分

$(function () {
  const imgJson = {
    arr:[]
  }
  /**
   * @description 转换文件成base64数据
   * @param {Object} file - 文件对象
   */
  function changeFileIntoBase64(file) {
    return new Promise((resolve, reject) => {
      const fr = new FileReader();
      fr.readAsDataURL(file);
      fr.onload = (result) => {
        const base64Str = result.currentTarget.result;
        resolve(base64Str);
      };
    });
  }

  /**
   * @description 初始化图片数据
   */
  async function initImgArr() { 
    const fileLength = $("#imageButton")[0].files.length;
    let arr = [];
    for (let i = 0; i < fileLength; i++) {
      const file = $("#imageButton")[0].files[i];
      const base64Str = await changeFileIntoBase64(file);
      arr.push(base64Str);
    }
    imgJson.arr = arr
    console.log(imgJson, "imgJson");
   }

  $("#test").click(async () => {
    const fileLength = $("#imageButton")[0].files.length;
    let arr = [];
    for (let i = 0; i < fileLength; i++) {
      const file = $("#imageButton")[0].files[i];
      const base64Str = await changeFileIntoBase64(file);
      arr.push(base64Str);
    }
    console.log(arr, "arr");
  });

  // 监听上传控件的change事件
  $("#imageButton").on("change", () => {
    initImgArr()
  });
});

输入结果如下图所示

【html + 原生js】input标签上传多张图片后如何转成base64数据并返回

目前支持点击获取or自动生成数组并赋值到指定对象下

各位如有更好的方案,欢迎留言...就是这样...