简体   繁体   中英

Python http post a file using request library

I have to post a file along with some data to to api. Here is the python code i wrote for testing:

fl={'payload' : open('C:/data/log2.txt')}
params = {
        'topic':'pos',
        'store':storeID,
         }

r = requests.post(url,files=fl,data=params)

print r.status
print r.text

But i always get a message saying, "file is not in correct format"

I tested the api with POSTMAN (chrome extension to test rest API) and it seems to work fine with postman i get a success response and the file is sent, here is a snapshot.

使用邮递员的api测试

From the docs

>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

Try adding 'rb' to your open statement so that you are uploading binary data.

Change

fl={'payload' : open('C:/data/log2.txt')}

to

fl={'payload' : open('C:/data/log2.txt', 'rb')}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM