如何从Base 64 String获取MIME-TYPE? [英] How to get MIME-TYPE from Base 64 String?
问题描述
我正在从后端获取字符串的base64,然后用Javascript对其进行解码以在浏览器上显示.
I am getting base64 for string from backend and i am then decoding it in Javascript to show on browser.
此字符串可以是任何文件.pdf,.img,.docx,.zip等.
This string can be any file .pdf, .img, .docx, .zip etc.
我的base64字符串不包含mime类型,例如'data:application/pdf; base64'部分.所以我需要获得base64的mime类型.
My base64 string does not include the mime-type for example 'data:application/pdf;base64' part. So i need to get mime type of base64.
有什么方法可以使用Javascript或Jquery解决此解决方案?
Is there any way to solve this solution with Javascript or Jquery?
推荐答案
您可以使用魔术数字以检测MIME类型(在此处文件签名列表).但是,文件签名不是100%可靠的,因此您很容易遇到误报.当然,有些任务还需要解决方案.
You can use magic numbers to detect a MIME type (check here the list of file signatures). However, file signatures are not 100% reliable and you can easily encounter false positives. Of course, there are tasks when a such solution is more than enough.
因此,如果您具有Base64字符串,并且想要使用文件签名来标识其MIME类型,则无需解码Base64.一种更快的方法是将文件签名存储为Base64,然后检查输入是否以其中之一开头.一个简单的例子:
So if you have a Base64 string and want to identify its MIME type using file signatures you don't need to decode the Base64. A much faster way is to store the file signatures as Base64 and just check if input starts with one of them. A simple example:
var signatures = {
JVBERi0: "application/pdf",
R0lGODdh: "image/gif",
R0lGODlh: "image/gif",
iVBORw0KGgo: "image/png"
};
function detectMimeType(b64) {
for (var s in signatures) {
if (b64.indexOf(s) === 0) {
return signatures[s];
}
}
}
// Some tests
console.log(detectMimeType('R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs='));
console.log(detectMimeType('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4z8AAAAMBAQD3A0FDAAAAAElFTkSuQmCC'));
console.log(detectMimeType('JVBERi0xLjUKJYCBgoMKMSAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvRmlyc3QgMTQxL04gMjAvTGVuZ3'));
这篇关于如何从Base 64 String获取MIME-TYPE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!