'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



Solution 1:[1]

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.

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 traktor
Solution 2 Yogi