[Django]-Django – Get uploaded file type / mimetype

29👍

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"
👤moskrc

24👍

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(2048), mime=True)
    file.seek(initial_pos)
    return mime_type

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

4👍

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👍

Need to override the save method in the model class

def save(self, *args, **kwargs):
    if self.file and self.file.file:
        try:#Need to add a try catch such that in case a file is not being uploaded, then the mime_type is not assigned
            self.mime_type=self.file.file.content_type
        except:
            pass

Taking an assumption that our model has file column(FileField), and mime_type column (CharField)

Leave a comment