9

My API:

class FileView(APIView):
    parser_classes = (MultiPartParser,)
    def post(self, request):
        do something with request.FILES.dict().iteritems()

My requests file:

try:
    headers = {
        'content-type': "multipart/form-data",
        'authorization': "Basic ZXNlbnRpcmVcYdddddddddddddd",
        'cache-control': "no-cache",
    }
    myfile = {"file": ("filexxx", open(filepath, "rb"))}

    response = requests.request("POST", verify=False, url=url, data=myfile, headers=headers)

    print(response.text)
except Exception as e:
    print "Exception:", e

Error:

"Multipart form parse error - Invalid boundary in multipart: None"

What is right way to post the file? Thanks

requests.version '2.10.0'

BAE
  • 8,550
  • 22
  • 88
  • 171

1 Answers1

19

Removed 'content-type' from the headers, now it works

try:
    headers = {
        'authorization': "Basic ZXNlbnRpcmVcYdddddddddddddd",
        'cache-control': "no-cache",
    }
    myfile = {"file": ("filexxx", open(filepath, "rb"))}

    response = requests.request("POST", verify=False, url=url, data=myfile, headers=headers)

    print(response.text)
except Exception as e:
    print "Exception:", e
BAE
  • 8,550
  • 22
  • 88
  • 171
  • 2
    Let requests set the content-type. In the request headers, the value for `content-type='multipart/form-data; boundary=f0d7eb0b58c94f8ea3e665e28cffffdc'` where the boundary changes depending on the request. – Bamcclur Jul 08 '16 at 16:06
  • Yes! when `content-type='multipart/form-data` browser adds this `boundary` parama while post request.So from python it is unnecessary totally! Anti-scraping tools like Distill-Networks etc. can use this param to detect python scraper easily. – Learner Jul 03 '19 at 05:52
  • Whatttttttttt! I've had to find this solution for 3 days. – Loi Nguyen Huynh Apr 06 '21 at 04:21