简体   繁体   English

Python http使用请求库发布文件

[英]Python http post a file using request library

I have to post a file along with some data to to api. 我必须将一个文件和一些数据发布到api。 Here is the python code i wrote for testing: 这是我为测试编写的python代码:

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. 我用POSTMAN测试了api(chrome扩展到测试休息API),它似乎与postman一起工​​作得到成功的响应并且文件被发送,这是一个快照。

使用邮递员的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. 尝试将'rb'添加到open语句,以便上载二进制数据。

Change 更改

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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