【问题标题】:Python : POST a Multipart-Encoded FilePython:发布多部分编码文件
【发布时间】:2016-10-20 20:54:51
【问题描述】:

尝试使用 requests 模块上传文件,但遇到内部服务器错误,使用海报模块也是如此:

import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
files={'file': open(r'Users/.../test.zip', 'rb')}
headers_info = {
    'content-type': "multipart/form-data; boundary=---12345",
    'x-api-service-version': "1.0",
    'connection': "Keep-Alive",
    'authorization': "Basic XXXXXXX",
    'x-file-format': "decrypted",
    'cache-control': "no-cache",
    }

response = requests.post(url, data = payload , headers=headers_info , params=querystring , files=files)

print response.status_code
print response.text

我用 POSTMAN 测试了 api(用于测试 rest API 的 chrome 扩展),它似乎与邮递员一起工作得很好,我得到了一个成功的响应并且文件被上传了。

python的邮递员代码显示:

import requests
url = "abc.com/upload"
querystring = {"ft":"1","fn":"filename"}
payload = ""
headers = {
    'content-type': "multipart/form-data; boundary=---12345",
    'accept-encoding': "gzip, deflate",
    'x-api-service-version': "1.0",
    'connection': "Keep-Alive",
    'authorization': "Basic XXXXXXX",
    'x-file-format': "decrypted",
    'cache-control': "no-cache",
    'postman-token': "XXXXXXX"
    }

response = requests.request("POST", url, data=payload, headers=headers, params=querystring)

print(response.text)

有相同的建议吗?我错过了什么明显的东西吗?感谢您可以分享的任何指针!

【问题讨论】:

标签: python-requests postman


【解决方案1】:

您不必指定'content-type': "multipart/form-data; boundary=---12345", 以及空data。尝试在没有headers 的情况下发送请求

response = requests.post(url, params=querystring , files=files)

如果失败,您可以尝试添加 'authorization': "Basic XXXXXXX", 'postman-token': "XXXXXXX" 标头

【讨论】:

    猜你喜欢
    • 2021-10-21
    • 2016-06-13
    • 2018-01-14
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 2018-06-17
    • 1970-01-01
    相关资源
    最近更新 更多