Django - 获取上传的文件类型/ mimetype [英] Django - Get uploaded file type / mimetype

查看:637
本文介绍了Django - 获取上传的文件类型/ mimetype的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在覆盖模型保存方法时,有没有办法获取上传文件的内容类型?我已经尝试过:

Is there a way to get the content type of an upload file when overwriting the models save method? I have tried this:

def save(self):
    print(self.file.content_type)
    super(Media, self).save()

但它没有工作。在这个例子中,self.file是一个model.FileField:

But it did not work. In this example, self.file is a model.FileField:

file = models.FileField(upload_to='uploads/%m-%Y/')

编辑:我想要将内容类型保存到数据库,所以我需要它之前保存实际完成:)

I want to be able to save the content type to the database, so I'll need it before the save is actually complete :)

推荐答案

class MyForm(forms.ModelForm):

    def clean_file(self):
        file = self.cleaned_data['file']
        try:
            if file:
                file_type = file.content_type.split('/')[0]
                print file_type

                if len(file.name.split('.')) == 1:
                    raise forms.ValidationError(_('File type is not supported'))

                if file_type in settings.TASK_UPLOAD_FILE_TYPES:
                    if file._size > settings.TASK_UPLOAD_FILE_MAX_SIZE:
                        raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.TASK_UPLOAD_FILE_MAX_SIZE), filesizeformat(file._size)))
                else:
                    raise forms.ValidationError(_('File type is not supported'))
        except:
            pass

        return file

settings.py

settings.py

TASK_UPLOAD_FILE_TYPES = ['pdf', 'vnd.oasis.opendocument.text','vnd.ms-excel','msword','application',]
TASK_UPLOAD_FILE_MAX_SIZE = "5242880"

这篇关于Django - 获取上传的文件类型/ mimetype的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆