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

时间:2019-04-12 13:57:20

标签: python python-3.x python-requests

我正在尝试通过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)

我怎么了?

1 个答案:

答案 0 :(得分:1)

您应该改用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
)