Meet101
Meet101

Reputation: 801

How to send excel file in multipart/form-data with POST Requests in python?

I am trying to send an excel file to server in POST Request in multipart/form-data content-type. I am getting an error:

too many values to unpack

What could be the reason? Below is the request what I am trying:

#Data = get_data('C:\foo.xls')
#print Data
Data = open('C:\foo.xls', 'rb')
print Data

headers = {
       'access-control-allow-origin': '*',
       'accept': 'application/json',
       'content-type': 'multipart/form-data', 
       'authorization': 'Basic xxxxxxxxx'
      }   
 R = requests.post('http://testserver:8080/v1/readyapi/executions/'+executionId+'/files', headers=headers, params=params, files=Data)
 print R.content

here is the error:

Traceback (most recent call last):
    (body, content_type) = self._encode_files(files, data)
  File "C:\Python27\lib\site-packages\requests\models.py", line 132, in _encode_files
    for (k, v) in files:
ValueError: too many values to unpack

I could not figure out by myself. tried few things, didn't work. Can someone please advise?

Upvotes: 1

Views: 19210

Answers (2)

lopof
lopof

Reputation: 1

Try this, right MIME type is important (https://wiki.selfhtml.org/wiki/MIME-Type/%C3%9Cbersicht)

headers = {
       'access-control-allow-origin': '*',
       'accept': 'application/json',
       'content-type': 'multipart/msexcel', 
       'authorization': 'Basic xxxxxxxxx'
      }

Upvotes: 0

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11665

Try the following code

Data = open('C:\foo.xls', 'rb') 
headers = {
       'access-control-allow-origin': '*',
       'accept': 'application/json',
       'content-type': 'multipart/form-data', 
       'authorization': 'Basic xxxxxxxxx'
      }
 files = {"file_name": Data}
 url = 'http://testserver:8080/v1/readyapi/executions/'+executionId+'/files'
 R = requests.post(url, headers=headers, params=params, files=files)
 print R.content

You must have to pass the files argument as a dictionary or you can also try like below

files = {'file': ('foo.xls', open('foo.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

Reference: http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

Upvotes: 2

Related Questions