使用 requests 的 post files 请求,发现服务端没法接受到文件,总提示请上传图片
F12 分析请求结构,主要看接口类型、请求头、Payload。
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryO3dY4lwWKYZkUXxq
使用 requests-toolbelt 库
import requests
from requests_toolbelt import MultipartEncoder
def upload_img(self, img_path, where):
"""
图片上传
:param img_path:
:param where:
:return:
"""
# https://requests.readthedocs.io/projects/cn/zh_CN/latest/user/quickstart.html#id4
api = urljoin(self.domain, "/backend/upload/image")
# image_open = open(img_path, 'rb')
img_name = os.path.basename(img_path)
img_open = open(img_path, 'rb')
img_mime = magic.from_file(img_path, mime=True)
# print(img_name, img_open, img_mime)
# 请求参数
data = MultipartEncoder(
fields={"type": where,
'image': (img_name, img_open, img_mime)}
)
# 构造请求头
self.headers["Content-Type"] = data.content_type
self.headers["Referer"] = "http://test.com/img/change"
res = requests.post(api, headers=self.headers, data=data)
if res.status_code == 200:
image_url = res.json().get("image")
print(image_url)
return image_url
else:
print(res.text)
return None