Skip to main content
 首页 » 编程设计

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

2024年10月01日7itcoder

我目前正在尝试将 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" 
} 

"file"字段显示为空,这对我来说有点奇怪。 POST 请求在 Postman 上运行,我在其中使用相同的 header 参数并使用“表单数据”选项将图像添加到正文(请参阅 Screenshot)。

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

提前谢谢你。

编辑:有人提出了类似的问题 here正如另一位用户指出的那样。但是,如果您查看它,我当前的代码与建议的解决方案类似,但它仍然对我不起作用。

请您参考如下方法:

使用这个片段

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)