使用Python Requests发送图片的POST请求

9

我目前正在尝试使用Python(3.5)和Requests库发送POST请求。这个POST请求将会发送一个图片文件。以下是示例代码:

import requests

url = "https://api/address"

files = {'files': open('image.jpg', 'rb')}
headers = {
    'content-type': "multipart/form-data",
    'accept': "application/json",
    'apikey': "API0KEY0"
    }
response = requests.post(url, files=files, headers=headers)

print(response.text)

然而,当我运行代码时,我收到了400错误。我已经成功访问了API端点,但响应中指出我没有发送任何文件。

{
  "_id": "0000-0000-0000-0000", 
  "error": "Invalid request", 
  "error_description": "Service requires an image file.", 
  "processed_time": "Tue, 07 Nov 2017 15:28:45 GMT", 
  "request": {
    "files": null, 
    "options": {}, 
"tenantName": "name", 
"texts": []
  }, 
  "status": "FAILED", 
  "status_code": 400, 
  "tenantName": "name"
}

“files”字段看起来是空的,这有点奇怪。在Postman上,我的POST请求成功了,其中我使用了相同的标头参数,并使用“form-data”选项将图像添加到正文中(请参见屏幕截图)。
我错过了什么吗?有没有更好的方法用Python发送图片文件?
提前感谢您。
编辑:另一个用户指出,这里曾经问过类似的问题。但是,如果您查看它,您会发现我的当前代码与被建议作为解决方案的代码类似,但对我仍然不起作用。

2
可能是使用Python-requests上传POST表单数据中的图像的重复问题。 - joppich
你好joppich。如果你仔细看一下,我的当前代码与建议的解决方案类似,但对我仍然无效。 - spdasilv
您提供了错误的Content-type。 - Harshith Thota
1个回答

10
使用这段代码片段:
import os
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接