使用Python请求通过POST请求发送图像

2024-05-17 05:41:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在尝试使用Python(3.5)和请求库来发送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"
}

“文件”字段显示为空,这对我来说有点奇怪。POST请求在Postman上工作,在Postman上,我使用了相同的头参数,并使用“form data”选项向主体添加了图像(请参见Screenshot)。

有什么我遗漏的吗?有没有更好的方法用python通过POST发送图像文件?

提前谢谢你。

编辑:另一个用户提出了类似的问题here。但是,如果您仔细研究,我当前的代码与建议的解决方案类似,但它仍然不适用于我。


Tags: 文件代码imageformurldataresponserequest
1条回答
网友
1楼 · 发布于 2024-05-17 05:41:36

使用此片段

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)

相关问题 更多 >