I am creating a method that uploads a file however I want to check the file size since I just want to allow 5mb as the max limit.
I want to make something like this
def handle_uploaded_file(thisFile):
if thisFile > 5mb:
return "This file is more than 5mb"
else:
with open('some/file/' + str(thisFile), 'wb+') as destination:
for chunk in thisFile.chunks():
destination.write(chunk)
return "File has successfully been uploaded"
# Add to your settings file
CONTENT_TYPES = ['image', 'video']
# 2.5MB - 2621440
# 5MB - 5242880
# 10MB - 10485760
# 20MB - 20971520
# 50MB - 5242880
# 100MB 104857600
# 250MB - 214958080
# 500MB - 429916160
MAX_UPLOAD_SIZE = 5242880
#Add to a form containing a FileField and change the field names accordingly.
from django.template.defaultfilters import filesizeformat
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
def clean_content(self):
content = self.cleaned_data['content']
content_type = content.content_type.split('/')[0]
if content_type in settings.CONTENT_TYPES:
if content._size > settings.MAX_UPLOAD_SIZE:
raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content._size)))
else:
raise forms.ValidationError(_('File type is not supported'))
return content
Credit goes to django snippet
Use ._size
file attribute
if thisFile._size > 5242880:
return "This file is more than 5mb"
._size
is represented in bytes. 5242880 - 5MB
def handle_uploaded_file(thisFile):
if thisFile._size > 5242880:
return "This file is more than 5mb"
else:
with open('some/file/' + str(thisFile), 'wb+') as destination:
for chunk in thisFile.chunks():
destination.write(chunk)
return "File has successfully been uploaded"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.