怎么判断文件类型?通过文件名后缀?这是完全不可靠的,有绝对可靠的方式吗?没有
相对可靠的方式就是通过文件文件内容(二进制流)来判断(极少数文件类型没有特殊的文件头或者特征,这种方式也判断不出来)
python 生态下,有什么已经封装好的,可以通过文件内容判断文件类型的包吗?有,经典的就是 filetype ,以及谷歌 2024年使用 AI 做的 magika
filetype 的优点就不说了,缺点就是这个包从 2022 年之后就不维护了: https://pypi.org/project/filetype/#history
至于 Magika 的情况,可以参考:Rust + AI!谷歌 Magika 1.0 把文件识别提升到新高度
然后提供一下使用案例
filetype 案例:用户传过来的图像需要保存在 oss 中,怎么做图片格式判断?基于不要相信客户端的原则,客户传过来的 cat.jpg 实际可能是 png 甚至 gif
下面提供了一个 filetype 的用法示例
把图片上传到 aliyun oss 的时候,需要设置 content_type 和 suffix
import filetype
def upload_image(self, stream: bytes, suffix: str) -> str:
"""
上传图片对象到 oss
"""
extension = None
mime = None
result = filetype.guess(stream)
if result:
extension = result.extension
mime = result.mime
self.upload_stream(stream, content_type=mime,
prefix='xxxxx', suffix=extension)
def upload_stream(self, stream: bytes, content_type: str | None, prefix: str, suffix: str | None) -> str:
"""
上传二进制对象到 oss
"""
hashcode = get_stream_md5(stream)
file_like_obj = io.BytesIO(stream)
oss_file_path: str = f'{prefix}/{hashcode}' + /
(f'.{suffix}' if suffix else '')
self.bucket.put_object(
oss_file_path,
file_like_obj,
headers={'Content-Type': content_type} if content_type else None
)
return oss_file_path
IT极限技术分享汇