Python 调用接口进行文件上传的踩坑记录

2022-09-26 18:13:25 浏览数 (1)

postman 接口调用

urllib3 的方式

代码语言:javascript复制
def upload_bak(content):
    """from urllib3 import encode_multipart_formdata"""
    filename = '测试报告6.png'
    url = HOST   "/api/v1/objectStore/bucket/bug/object"
    headers = HEADERS
    files = {'file': (filename, content), 'objectName': filename}
    encode_data = encode_multipart_formdata(files)
    file_data = encode_data[0]
    headers['Content-Type'] = encode_data[1]
    response = requests.request("PUT", url, headers=headers, data=file_data)
    print(response.text)

MultipartEncoder 方式

代码语言:javascript复制
def upload(content):
    """from requests_toolbelt import MultipartEncoder"""
    filename = '测试报告4.png'
    url = HOST   "/api/v1/objectStore/bucket/bug/object"
    headers = HEADERS
    encoded_name = urllib.quote(filename)
    m = MultipartEncoder(
        fields={'file': (encoded_name, content),
                'objectName': filename}
    )
    decoded_m = m.to_string()
    decoded_m = decoded_m.replace(encoded_name, filename)
    headers['Content-Type'] = m.content_type
    response = requests.request("PUT", url, headers=headers, data=decoded_m)
    print(response.text)

版权声明:如无特殊说明,文章均为本站原创,转载请注明出处 本文链接:https://cloud.tencent.com/developer/article/2123570 许可协议:署名-非商业性使用 4.0 国际许可协议

0 人点赞