Danny van der Aa
Danny van der Aa

Reputation: 15

How to upload a file using requests in Python

I am trying to upload a file via Python requests and i receive an error code 400 (Bad request)

#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)

If i try via Postman this is successfull using following code.

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)

What do i wrong?

Upvotes: 1

Views: 91

Answers (1)

blhsing
blhsing

Reputation: 106936

You should use the files parameter instead. Also, don't explicitly set Content-Type in the header so that requests can set it for you with a proper boundary:

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
)

Upvotes: 1

Related Questions