|
7 | 7 |
|
8 | 8 | import magic
|
9 | 9 |
|
| 10 | + |
10 | 11 | class ValidatedFileField(models.FileField):
|
11 | 12 | def __init__(self, *args, **kwargs):
|
12 | 13 | self.content_types = kwargs.pop("content_types", [])
|
13 | 14 | self.max_upload_size = kwargs.pop("max_upload_size", 0)
|
| 15 | + self.mime_lookup_length = kwargs.pop("mime_lookup_length", 4096) |
14 | 16 | super(ValidatedFileField, self).__init__(*args, **kwargs)
|
15 | 17 |
|
16 | 18 | def clean(self, *args, **kwargs):
|
17 | 19 | data = super(ValidatedFileField, self).clean(*args, **kwargs)
|
18 | 20 | file = data.file
|
19 | 21 |
|
20 | 22 | if self.content_types:
|
21 |
| - content_type_headers = getattr(file, 'content_type', '') |
| 23 | + uploaded_content_type = getattr(file, 'content_type', '') |
22 | 24 |
|
23 |
| - mg = magic.Magic(mime = True) |
24 |
| - content_type_magic = mg.from_buffer(file.read(1024)) |
| 25 | + mg = magic.Magic(mime=True) |
| 26 | + content_type_magic = mg.from_buffer( |
| 27 | + file.read(self.mime_lookup_length) |
| 28 | + ) |
25 | 29 | file.seek(0)
|
26 | 30 |
|
27 |
| - if not content_type_headers in self.content_types or not content_type_magic in self.content_types: |
| 31 | + # Prefere mime-type instead mime-type from http header |
| 32 | + if uploaded_content_type != content_type_magic: |
| 33 | + uploaded_content_type = content_type_magic |
| 34 | + |
| 35 | + if not uploaded_content_type in self.content_types: |
28 | 36 | raise forms.ValidationError(_('Files of type %(type)s are not supported.') % {'type': content_type_magic})
|
29 | 37 |
|
30 |
| - if self.max_upload_size: |
| 38 | + if self.max_upload_size and hasattr(file, '_size'): |
31 | 39 | if file._size > self.max_upload_size:
|
32 | 40 | raise forms.ValidationError(_('Files of size greater than %(max_size)s are not allowed. Your file is %(current_size)s') %
|
33 | 41 | {'max_size': filesizeformat(self.max_upload_size),
|
@@ -76,4 +84,4 @@ def __call__(self, file):
|
76 | 84 | raise forms.ValidationError(_('Please keep the total uploaded files under %(total_size)s. With this file, the total would be %(exceed_size)s.' %
|
77 | 85 | {'total_size': filesizeformat(self.quota.max_usage),
|
78 | 86 | 'exceed_size': filesizeformat(self.quota.current_usage + file_size)}))
|
79 |
| - |
| 87 | + |
0 commit comments