1

Here I,m using Django-REST framework for file upload, I'm not using a model layer in Django. So I am using default_storage for the uploaded file to save. My question here is how would I validate the files. Uploaded file should not exixts 10mb.Thanks in Advance.

class imageapi(APIView):
    def post(self, request):

        if request.method == 'POST' and request.FILES['file']:
            try:

                form = UploadFileForm(request.POST, request.FILES)
                #save_path = os.path.join(settings.MEDIA_ROOT, 'uploads', request.FILES['file'])

                save_path = str(settings.MEDIA_ROOT)+ '/uploads/'+str(request.FILES['file'])
                path = default_storage.save(str(save_path), request.FILES['file'])
                return Response({default_storage.path(path)})
            except Exception as ex:
                return Response({"DATA": str(ex)})

2 Answers 2

1

1. The django way:

You can check the size of the file in your form like this: field_name.size. This will return the size in bytes.

2. The server way:

You can configure your frontend server (Nginx, or Apacher, or whatever you're using) not to accept files more than 10 mb. This approach is better and safer.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks @xyres .. will you share some code in python to validate
@selvakumar check docs on field validation: docs.djangoproject.com/en/2.1/ref/forms/validation/…
0

Multiple answers here on stackoverflow and the official docs suggest handling this on your webserver.

If using nginx, you can limit the filesize by using the client_max_body_size in the http block:

http {
    ...
    client_max_body_size 10M;
}    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.