In Django I have a view for uploading a file. I want to limit the possible file size to 0.5MB. This is how I do it today:
class FileUploadView(BaseViewSet):
parser_classes = (MultiPartParser, FormParser)
serializer_class = FileUploadSerializer
def create(self, request, *args, **kwargs):
file_serializer = self.get_serializer(data=request.data)
file_serializer.is_valid(raise_exception=True)
file_ = file_serializer.validated_data['file']
class FileUploadSerializer(serializers.ModelSerializer):
file = MyFileField()
MAX_UPLOAD_SIZE = 500000 # max upload size in bytes. 500000 = 0.5MB
def validate_file(self, received_file):
if received_file.file.size > self.MAX_UPLOAD_SIZE:
raise BadRequestException(
message='File size is bigger than 0.5MB',
error_type=ExceptionTypeEnum.IMPORT_FILE_SIZE_TOO_BIG
)
It works. My problem is that the file must first be uploaded to the server before evaluating the size. I checked for other possible options.
I can use DATA_UPLOAD_MAX_MEMORY_SIZE (which currently has the default value of 2.5MB) but I don't want to change it to 0.5MB for all the requests.
I guess that I may use the 'content-length' header, but seems like it's only after uploading as well.
I was wondering if there's a way to reject large files before actually uploading them (In Backend).