回到顶部

阅读目录

python requests post 使用 multipart/form-data 上传文件方法

发生背景

使用 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

 


^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!

前一篇: pymysql in 的写法
下一篇: django admin $ is not a function
captcha