James Reid James Reid - 4 months ago 12
Python Question

How to check the file size limit in django

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"

Answer

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"