繁体   English   中英

如何使用 Python 中的请求上传文件

[英]How to upload a file using requests in Python

我正在尝试通过 Python 请求上传文件,但收到错误代码 400(错误请求)

#Update ticket with upload of CSV file
header_upload_file = {
            'Authorization': 'TOKEN id="' + token + '"',
            'Content-Type': 'multipart/form-data'
}

files = {
            'name': 'file',
            'filename': open(main_path + '/temp/test.txt', 'rb'),
            'Content-Disposition': 'form-data'
        }


response = requests.post(baseurl + '/incidents/number/' + ticket_number + '/attachments/', headers=header_upload_file, data=files, verify=certificate)

如果我通过邮递员尝试使用以下代码成功。

url = "https://<url>"
payload = "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"file\"; filename=\"C:\\Users\\<filename>\"\r\nContent-Type: text/csv\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--"
headers = {
'content-type': "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
'Authorization': "TOKEN id="3e9d095d-a47b-48b5-a0b8-ae8b8ad9ae74"",
'cache-control': "no-cache",
'Postman-Token': "bb155176-b1b8-47a6-8fb3-46f5740cf9e0"
}

response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)

我怎么了?

您应该改用files参数。 此外,不要在标头中显式设置Content-Type以便requests可以为您设置适当的边界:

header_upload_file = {
    'Authorization': 'TOKEN id="' + token + '"'
}
response = requests.post(
    baseurl + '/incidents/number/' + ticket_number + '/attachments/',
    headers=header_upload_file,
    files={'file': ('file', open(main_path + '/temp/test.txt', 'rb'), 'text/csv')},
    verify=certificate
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM