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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28356367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:26:37  来源:igfitidea点击:

Retrieve MIME type from Base64 encoded String

javabase64mime

提问by codereviewanskquestions

Let' say a file (e.g. myfile.jpeg) encoded in Base64 String and given to me. 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 (e.g jpeg)?

假设一个文件(例如 myfile.jpeg)以 Base64 字符串编码并提供给我。我无法知道文件类型是什么。我想将字符串解码成一个文件(在这个例子中是一个图像)。我如何知道文件的类型(例如 jpeg)?

回答by Andy Turner

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. You'd still need to do more work to determine if it is a valid JPEG image.

要确定它是否是 JPEG 图像的实例,您需要对其进行 base64 解码,然后执行诸如检查其幻数之类的操作,这有助于告诉您文件不是什么。您仍然需要做更多的工作来确定它是否是有效的 JPEG 图像。

回答by F.O.O

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=

数据:图像/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABfbf4CY

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。假设图像来自受信任的客户端。