[英]Sending image over POST request with Python Requests
我目前正在嘗試使用 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"
}
“文件”字段顯示為空,這對我來說似乎有點奇怪。 POST 請求在 Postman 上工作,我使用相同的標頭參數並使用“form-data”選項將圖像添加到正文中(請參閱屏幕截圖)。
有什么我在這里想念的嗎? 有沒有更好的方法通過 POST 使用 python 發送圖像文件?
提前謝謝你。
編輯:如另一位用戶所指出的, 這里提出了一個類似的問題。 但是,如果您查看它,我當前的代碼與建議的解決方案類似,但它仍然對我不起作用。
使用這個片段
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.