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

659
Visualizações
Get MIME type and extension from base64 string in Javascript

I have a base64 string like this:

JVBERi0xLjUNJeLjz9MNCjEwNzYgMCBvYmoNPDwvTGluZWFyaXplZCAxL0wgMjE0MDcyL08gMTA3OC9FIDE4ODA0OS9OIDgvVCAyMTM2NTAvSCBbIDUwMiAyMzNdPj4NZW5kb2JqDSAgICAgICAgICAgDQoxMDkyIDAgb2JqDTw8L0RlY29kZVBhcm1zPDwvQ29sdW1ucyA1L1ByZWRpY3RvciAxMj4+L0ZpbHRlci9GbGF0ZURlY29kZS9JRFs8NjU2QTUwQkZGRjE4Q0I0QzgyNDQ1N0QwOTcxN0NGRUQ+PDJDMDgyNjNGMzczNDUxNENCMUZERjE1RkQ5RjgxMEM0Pl0vSW5kZXhb...etc...

Is it possible to decode it and get MIME type and extension from it? I know a way using magic numbers, mentioned in the top comment here: How to get MIME-TYPE from Base 64 String?

But in my app, user can upload any type of file he wants, so what should I do?

For example, this page decodes base64 string and returns both extension and MIME type, so I know it's possible:https: //base64.guru/converter/decode/file

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

0

On the front end, capture the mime type of the file chosen to be uploaded by the user( it's a property of a file object) and include the mime type in the upload (fetch, axios, formdata, post, whatever) sent to the server.

about 4 years ago · Juan Pablo Isaza Relatório

0

To illustrate @traktor solution....

OP notes that it's not possible to upload additional metadata like mime type, yet that is not necessary because the mime type is already included in the base64 string that is generated.

Example output:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEA...
data:text/plain;base64,ZXlKamIyMXRaVzUwY3lJNlczc2l...
data:text/html;base64,PCFkb2N0eXBlIGh0bWw+DQo8aHRt...
data:application/pdf;base64,JVBERi0xLjcKCjQgMCBvYm...
data:application/vnd.openxmlformats-officedocument...

Run the code snippet to try:

upload.onchange = function(e) {
  for (var f of e.target.files) {
    const reader = new FileReader();
    reader.readAsDataURL(f);
    reader.onload = () => console.log(reader.result.substring(0, 50) + "...");
  }
}
Select multiple file types for upload:<br/>

<input type="file" multiple="true" id="upload">

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