0

to simplify:

curl --location --request PUT 'https://myserver.com/upload' \
--form 'file=@/Users/myname/Desktop/bond.jpg' \
--form 'test=test'

It gets to my Django App:

class MyUploadView(APIView):
    parser_classes = [FormParser, MultiPartParser]
    
    def put(self, request, **kwargs):
        print(request.FILES)  
  

but gives out: <MultiValueDict: {}>

nothing I do work, file is always empty. when I use Content-Type: multipart/form-data it doesn't work as well, and sometimes django would complain there is no boundary -- but any value there gives out the same error.

MY GOAL IS SIMPLE: all I want it to upload a file to django and save it to disk on the backend.

I cannot believe this i taking all day long with zero results and zero examples online that actually work.

JasonGenX
  • 4,952
  • 27
  • 106
  • 198

1 Answers1

3

You don't mention that you are developing a REST API but I'm assuming that from your use of FormParser and MultiPartParser.

In the example in the Django REST framework it uses request.data['file'] not request.FILES as you have in your code.

Try changing your method to

def put(self, request, **kwargs):
    print(request.data['file'])

and see if you get any output.

To save the uploaded file you can do this:

def put(self, request, **kwargs):
    uploaded_file = request.data['file']
    destination = open('/Users/Username/' + uploaded_file.name, 'wb+')
    for chunk in uploaded_file.chunks():
        destination.write(chunk)
    destination.close()
    return Response(uploaded_file.name, status.HTTP_201_CREATED)

This code borrowed from other posts on SO, such as this one:

Django Rest Framework File Upload

Tony
  • 9,672
  • 3
  • 47
  • 75