Files (except pdfs) Corrupted when uploading django restframework api

Viewed 425

Hey so i'm having a bit of an issue. I wrote a django restframework api for uploading files to my local directory. It seems like it works perfectly fine when it comes to pdfs, but any other type of format damages the file and make it unable to open.

(this includes png/jpg/any other picture format, txt files, xlsx files, and etc) The files are saved perfectly fine in the correct path, they're named appropriately without issue.

class UploadInvoiceFile(APIView):
     parser_classes = (FileUploadParser, MultiPartParser)

     def put(self, request, filename, specific_path='admin'):
         file_obj = request.data['file']
         file_path = settings.INVOICE_URL[admin]
         file = file_path+'/'+filename

         if not os.path.exists(file_path):
             os.makedirs(file_path)
         with open(file, 'wb+') as destination:
             for chunk in file_obj.chunks():
                 destination.write(chunk)



         return Response(status=204)

UPDATE: I found out that the files that are curropted have additional stuff saved to them

------WebKitFormBoundaryKDALl9LeBZb6xbOo Content-Disposition: form-data; name="file"; filename="123.txt" Content-Type: text/plain

file data

------WebKitFormBoundaryKDALl9LeBZb6xbOo--

1 Answers

The FileUploadParser assumes that an incoming request is a raw byte stream and parses it as a whole. It's typically listed on its own in parser_classes since it will activate for any type of incoming data.

What's happening in your case, is that you're sending a multipart request which is being picked up by FileUploadParser and the whole thing - boundaries and all - saved as a file. Hence you see the WebKitFormBoundary in the files.

You should drop FileUploadParser from parser_classes and let the MultiPartParser correctly parse the multipart request.

class UploadInvoiceFile(APIView):
     parser_classes = (MultiPartParser, )
Related