Django - Get uploaded file type / mimetype

前端 未结 4 1596
别那么骄傲
别那么骄傲 2020-12-13 15:26

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.cont         


        
相关标签:
4条回答
  • 2020-12-13 15:33
    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

    TASK_UPLOAD_FILE_TYPES = ['pdf', 'vnd.oasis.opendocument.text','vnd.ms-excel','msword','application',]
    TASK_UPLOAD_FILE_MAX_SIZE = "5242880"
    
    0 讨论(0)
  • 2020-12-13 15:35

    I'm using Django Rest Framework and this is the simplest way to determine content type/mime type:

    file = request.data.get("file")    # type(file) = 'django.core.files.uploadedfile.InMemoryUploadedFile'
    print(file.content_type)
    

    Let's say I have uploaded a JPEG image then my output would be:

    image/jpeg
    

    Let me know in the comments if this serves your purpose.

    0 讨论(0)
  • 2020-12-13 15:39

    You can use PIL or magic to read the few first bytes and get the MIME type that way. I wouldn't trust the content_type since anyone can fake an HTTP header.

    Magic solution below. For a PIL implementation you can get an idea from django's get_image_dimensions.

    import magic
    
    
    def get_mime_type(file):
        """
        Get MIME by reading the header of the file
        """
        initial_pos = file.tell()
        file.seek(0)
        mime_type = magic.from_buffer(file.read(1024), mime=True)
        file.seek(initial_pos)
        return mime_type
    

    File is the in-memory uploaded file in the view.

    0 讨论(0)
  • 2020-12-13 15:42

    I'm using Django Rest Framework and this is the simplest I could go:

    file = request.data.get("file")    # type(file) = 'django.core.files.uploadedfile.InMemoryUploadedFile'
    print(file.content_type)
    

    Let's say I have uploaded a JPEG image then my output would be:

    image/jpeg
    
    0 讨论(0)
提交回复
热议问题