【问题标题】:Get file mime type on pre_save in django admin在 django admin 中的 pre_save 上获取文件 mime 类型
【发布时间】:2020-07-21 17:16:51
【问题描述】:

我想通过 pre_save 信号来保存文件 mime 类型。

from django.db.models.signals import pre_save
from django.db import models
import magic

class Media (models.Media):
    file = models.FileField()
    content_type = models.CharField(max_length=128, editable=False)

def media_pre_save(sender, instance, *args, **kwargs):
    if not instance.content_type:
        mime = magic.Magic(mime=True)
        instance.content_type = mime.from_buffer(instance.file.read())
pre_save.connect(media_pre_save, sender=Media)

但是当我在 db 中查看它时,我得到了 application/x-empty。我做错了什么?

【问题讨论】:

标签: python django django-admin mime-types


【解决方案1】:

我终于想通了如何获取上传文件的绝对路径,并像这样使用magicfrom_file方法:

instance.content_type = magic.from_file(instance.file.path, mime=True)

更新答案:

如果文件有点大,我有时会得到空文件,所以我必须从上传文件的开头“寻找”并使用magicfrom_buffer 方法,如下所示:

instance.file.seek(0)
instance.content_type = magic.from_buffer(instance.file.read(), mime=True)

我欠以下链接的答案: Edit uploaded file (djangos FileField) using pre_save signalhttps://github.com/ahupp/python-magic

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 2018-12-01
    • 2011-07-03
    • 2014-02-20
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 2012-05-08
    • 2011-04-20
    相关资源
    最近更新 更多