简体   繁体   English

从 Base64 编码的字符串中检索 MIME 类型

[英]Retrieve MIME type from Base64 encoded String

Let' say a file (eg myfile.jpeg) encoded in Base64 String and given to me.假设一个文件(例如 myfile.jpeg)以 Base64 字符串编码并提供给我。 There is no way I know what the file type was.我无法知道文件类型是什么。 I'd like to decode the string into a file (an image in this example).我想将字符串解码成一个文件(在这个例子中是一个图像)。 How do I know the type of the file (eg jpeg)?我如何知道文件的类型(例如 jpeg)?

In general, a base 64-encoded string could contain absolutely any data, so there is no way to know its file type.一般情况下,base 64 编码的字符串可以包含绝对任何数据,因此无法知道其文件类型。

To determine if it is an instance of a JPEG image, you'd need to base64-decode it, and then do something like checking its magic number , which is useful in telling you what the file isn't .要确定它是否是 JPEG 图像的实例,您需要对其进行 base64 解码,然后执行诸如检查其幻数之类的操作,这有助于告诉您文件不是什么。 You'd still need to do more work to determine if it is a valid JPEG image.您仍然需要做更多的工作来确定它是否是有效的 JPEG 图像。

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=数据:图像/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABfbhXY/j//z8ABf4CQA

Is a sample image.是一个示例图像。 Just split it with the first slash and get array index 1. Supposing the image is coming from a trusted client.只需用第一个斜杠分割它并获得数组索引 1。假设图像来自受信任的客户端。

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

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