如何从flutter中的base64字符串获取文件扩展名|镖
我有一个来自API的文档的base64字符串。我想知道是哪种扩展/文件格式。因为如果它在jpg/jpeg/png中,我想在图像小部件中显示它。或者,如果是PDF格式,我想在PDFView窗口小部件中显示。因此,有什么方法可以从base64获取文件扩展名。有包裹吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有base64字符串,则可以通过检查base64字符串的第一个字符来检测文件类型:
'/'表示JPEG。
“我”的意思是png。
'r'表示gif。
'u'表示WebP。
'J'表示PDF。
我为此写了一个功能:
If you have a base64 string you can detect file type by checking the first character of your base64 string:
'/' means jpeg.
'i' means png.
'R' means gif.
'U' means webp.
'J' means PDF.
I wrote a function for that:
如果您没有原始文件名,则无法恢复它。那是元数据不是文件内容的一部分,而base64编码仅在文件的内容上运行。最好保存原始文件名,最好。
如果不能,则可以使用
package:mime
猜猜来自少量二进制数据的文件的MIME类型。您可以从base64字符串中解码第一个 n ×4个字符(有效的base64字符串必须具有4个倍数的长度),解码它,然后调用lookupmimetype
。软件包:Mime
具有 您可以动态计算 n 的值:对于
package:mime
支持写作时的类型,mime.defaultmagicnumbersmaxlength 为12(这转化为需要从base64字符串中解码前16个字节)。
If you don't have the original filename, there's no way to recover it. That's metadata that's not part of the file's content, and base64 encoding operates only on the file's content. It'd be best if you could save the original filename.
If you can't, you can use
package:mime
to guess the MIME type of the file from a small amount of binary data. You could decode the first n×4 characters from the base64 string (a valid base64 string must have a length that's a multiple of 4), decode it, and calllookupMimeType
.package:mime
has adefaultMagicNumbersMaxLength
value that you can use to compute n dynamically:For the types that
package:mime
supports as of writing,mime.defaultMagicNumbersMaxLength
is 12 (which translates to needing to decode the first 16 bytes from the base64 string).一种解决方案是使用魔法数字从base64检测到文件类型:
One solution would be detect File Type from Base64 Using Magic Numbers: