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

问题描述 投票:1回答:1

我试图通过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)

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

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)

我错了什么?

python python-3.x python-requests
1个回答
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
)
© www.soinside.com 2019 - 2024. All rights reserved.