Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
How to get json of base64 from file list

I get file list and want to make json array like

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

My code:

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

I can not use list as simple array. How Do I?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The map() method uses the return value of the function as it is See map() in MDN.

The variable list will contain a list of Promises instead of the intended object.

You should wrap the map with await Promise.all() See Promise.all() in MDN and make the function async to have the objects array.

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;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Its hard to be sure, but I think your issue is you are performing asyncronous operations within a map, so you need to ensure the promises resolve. I think this would solve your issue.

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)
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda