How do you create an API with Django Rest Framework that support file uploads?
What if your application needs to process the file immediately and return a response as soon as it is finished?
The file sizes can vary and you may also need to delete the file as soon as you’ve finished processing it.
DRF’s FileUploadParser is very helpful in this situation. Parsers are classes in DRF which helps your views handle different type of content.
FileUploadParser’s sole purpose is to handle raw file upload content.
To use it in your views, just put it as the sole parser in the parser_classes class variable.
Here’s the example taken from https://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser
class FileUploadView(views.APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204)
You can see in the example that the uploaded file object is accessed via request.data[‘file’]
FileUploadParser uses Django’s FILE_UPLOAD_HANDLERS settings. This means that by default, files smaller than 2.5MB are stored in memory and higher than that is stored in a temporary file on disk. This is done automatically for you.
Another important thing to notice is the filename parameter in the put() in the view. The filename is taken from the filename URL keyword argument. If it is not set, the filename should be set in the Content-Disposition header: Content-Disposition: attachment; filename=sample.txt
After all of these setup, you are now free to process the file and delete it after if you intended to.