【问题标题】:How to get json of base64 from file list如何从文件列表中获取base64的json
【发布时间】:2022-01-22 23:52:55
【问题描述】:

我得到文件列表并想制作 json 数组

[
  {"name":"IDCard001.jpg","base64":"data:image/jpeg;base64,/9j/4AA.."},
  {"name":"IDCard002.jpg","base64":"data:image/jpeg;base64,/9j/4AA.."},
]

我的代码:

  const getBase64 = (file: File) => {
    return new Promise((resolve, reject) => {
      let reader = new FileReader();
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
      reader.readAsDataURL(file);
    });
  };

  const handleFiles = (files: Array<File>) => {
    const list = files.map(async (file) => {
      return {
        name: file.name,
        base64: await getBase64(file),
      };
    });
  }

我不能将列表用作简单数组。我该怎么做?

【问题讨论】:

    标签: javascript typescript async-await promise


    【解决方案1】:

    map() 方法使用函数的返回值,因为它是See map() in MDN

    变量 list 将包含一个 Promises 列表,而不是预期的对象。

    您应该使用 await Promise.all() See Promise.all() in MDN 包装地图,并使函数异步以拥有对象数组。

    const handleFiles = async (files: Array<File>) => {
      const list = await Promise.all(files.map(async (file) => {
        return {
          name: file.name,
          base64: await getBase64(file),
        };
      }));
      return list;
    }
    

    【讨论】:

      【解决方案2】:

      很难确定,但我认为您的问题是您在地图中执行异步操作,因此您需要确保承诺得到解决。我认为这会解决您的问题。

      const handleFiles = async(files: Array<File>) => {
        const list = await Promise.all(files.map(async (file) => {
          return {
            name: file.name,
            base64: await getBase64(file),
          };
        }))
        console.log(list)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-15
        • 1970-01-01
        • 2012-11-12
        • 1970-01-01
        • 1970-01-01
        • 2021-10-13
        相关资源
        最近更新 更多