简体   繁体   English

从 Javascript 中的 base64 字符串获取 MIME 类型和扩展名

[英]Get MIME type and extension from base64 string in Javascript

I have a base64 string like this:我有一个 base64 这样的字符串:

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

Is it possible to decode it and get MIME type and extension from it?是否可以对其进行解码并从中获取 MIME 类型和扩展名? I know a way using magic numbers, mentioned in the top comment here: How to get MIME-TYPE from Base 64 String?我知道一种使用幻数的方法,在此处的顶部评论中提到: 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例如,此页面解码 base64 字符串并返回扩展名和 MIME 类型,所以我知道这是可能的:https: //base64.guru/converter/decode/file

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.在前端,捕获用户选择要上传的文件的 mime 类型(它是file object的属性)并在上传中包含 mime 类型(fetch、axios、formdata、post 等)发送到服务器。

To illustrate @traktor solution....说明@traktor 解决方案....

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. OP 指出,不可能上传其他元数据,如 mime 类型,但这不是必需的,因为 mime 类型已经包含在生成的 base64 字符串中。

Example output:示例 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">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM