如何用Python Requests向指定网站上传图片?请求失败排查
图片上传请求失败的问题排查与解决
问题背景
要上传本地文件user_photo_510495289.jpg到指定情感识别接口,网站给出的curl提交示例为:
curl -X POST -F "od_content=@1.jpg" https://srv2.demo.neural-university.ru/emotion_recognition/
用Python的requests.post尝试两种方式均失败,且发现接口预期接收JSON格式数据。
问题分析
- 请求格式矛盾:curl的
-F参数是发送multipart/form-data类型的表单请求,但你发现接口预期JSON,这里要么是网站的curl示例标注错误,要么是对接口的格式判断有误。 - 现有代码的问题:
- 使用
data参数时,直接传递文件二进制内容,会生成application/x-www-form-urlencoded格式的请求,既不符合curl示例的multipart/form-data,也不符合JSON格式要求 - 注释掉的
files参数代码才是对应curl-F的正确实现,但如果接口真的要求JSON,这种方式也不适用
- 使用
解决方式
情况1:接口确实需要JSON格式
将图片转为Base64编码后,封装到JSON字段中提交:
import requests import base64 url = 'https://srv2.demo.neural-university.ru/emotion_recognition/' # 读取图片并转为Base64编码 with open('user_photo_510495289.jpg', 'rb') as img_file: img_base64 = base64.b64encode(img_file.read()).decode('utf-8') # 构造JSON请求体 json_payload = {'od_content': img_base64} response = requests.post(url, json=json_payload) # 查看响应结果 print(response.status_code) print(response.text)
情况2:接口实际需要multipart/form-data格式
启用原本注释的files参数代码即可,这是对应curl示例的正确实现:
import requests url = 'https://srv2.demo.neural-university.ru/emotion_recognition/' files = {'od_content': open('user_photo_510495289.jpg', 'rb')} response = requests.post(url, files=files) # 查看响应结果 print(response.status_code) print(response.text)
内容的提问来源于stack exchange,提问作者SkyPan
相关产品推荐
相关产品推荐

