Updated

Using requests.put() with the files parameter sends a multipart/form-data encoded request which the server does not seem to be able to handle without corrupting the data, even when the correct content type is declared.

The curl command simply performs a PUT with the raw data contained in the body of the request. You can create a similar request by passing the file data in the data parameter. Specify the content type in the header:

headers = {'Content-type': 'image/jpeg', 'Slug': fileName}
r = requests.put(url, data=open(path, 'rb'), headers=headers, auth=('username', 'pass'))

You can vary the Content-type header to suit the payload as required.


Try setting the Content-type for the file.

If you are sure that it is a text file then try text/plain which you used in your curl command - even though you would appear to be uploading a jpeg file? However, for a jpeg image, you should use image/jpeg.

Otherwise for arbitrary binary data you can use application/octet-stream:

openBin = {'file': (fileName, open(path,'rb'), 'image/jpeg' )}

Also it is not necessary to explicitly read the file contents in your code, requests will do that for you, so just pass the open file handle as shown above.

Answer from mhawke on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-upload-files-using-python-requests-library
How to Upload Files Using Python Requests Library - GeeksforGeeks
July 23, 2025 - Before diving into file upload examples, let's ensure you have the requests library installed. If not, you can install it using pip: ... In this example, below code uses the Python requests library to upload a file (file.txt) to the specified URL (https://httpbin.org/post) using a POST request with the files parameter, and then prints the response text.
Discussions

File upload using REST API and Python requests - Development - Omeka Forum
Hi, I ran into an issue uploading a file to an Omeka Classic instance using Python requests. I tried to use code examples from here: Those examples are for Omeka S, so I modified my code in terms of credentials, so my… More on forum.omeka.org
🌐 forum.omeka.org
0
February 21, 2020
How to upload file with python requests? - Stack Overflow
The commented print statements ... upload_engagement_file are showing you how you can access them. Note: Some useful additional information about the requests library can be found here. If you want to learn more about Python (more general information), look here. ... Some may need to upload via a put request and ... More on stackoverflow.com
🌐 stackoverflow.com
Uploading files via API in Python
Hello all! There are bits and pieces of documentation that relate to this topic, but none that explicitly show how to use this mutation from Python (that I’ve been able to find). Basically, I’d like the query set up so that I have dynamic variables for both file (the image being uploaded) ... More on community.monday.com
🌐 community.monday.com
1
0
April 26, 2024
PUT (requests.put) specifying the source file location for zip file error 10054
C:\svn\libraries\cpp>python req_put.py default.zip Traceback (most recent call last): File "req_put.py", line 102, in resp = requests.put(uri, headers=headers, data=data) # data=data , params=payload) File "C:\Python27\lib\site-packages\requests\api.py", line 124, in put return ... More on github.com
🌐 github.com
5
January 31, 2017
🌐
ProxiesAPI
proxiesapi.com › articles › uploading-files-in-python-requests-a-guide
Uploading Files in Python Requests: A Guide | ProxiesAPI
... multipart encodes file data separately allowing large binary payloads to be transferred efficiently. ... Uploading a file is just a matter of attaching the binary data as well as metadata to identify the file contents.
🌐
Stack Abuse
stackabuse.com › how-to-upload-files-with-pythons-requests-library
How to Upload Files with Python's requests Library
September 19, 2021 - This tutorial covers how to send the files, we're not concerned about how they're created. To follow along, create three files called my_file.txt, my_file_2.txt and my_file_3.txt. The first thing we need to do is install our the request library in our workspace.
🌐
Crazyeights225
crazyeights225.github.io › pyrequests
Tutorial: Uploading Files with Python Requests -
December 31, 2020 - <input name="firstname">) # the server usually doesn't use the filename, and instead names the file something random # we also use this format for any other fields in the form # WordPress requires a nonce, and the referrer field in order for the request to be successful data = { '_wpnonce': (None, wp_nonce), '_wp_http_referer': (None, "/wordpress/wp-admin/plugin-install.php?tab=upload"), 'install-plugin-submit': (None, 'Install Now'), 'pluginzip': (resource_path, open(resource_path, 'rb'), "application/octet-stream") } resp = requests.post(url_admin_update, files=data, cookies=wp_init_cookies) print(resp.status_code)
🌐
TutorialsPoint
tutorialspoint.com › requests › requests_file_upload.htm
File Upload with Requests in Python
import requests myurl = 'https://httpbin.org/post' files = {'file': open('test.txt', 'rb')} getdata = requests.post(myurl, files=files) print(getdata.text) ... E:\prequests>python makeRequest.py { "args": {}, "data": "", "files": { "file": "File upload test using Requests" }, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "175", "Content-Type": "multipart/form-data; boundary=28aee3a9d15a3571fb80d4d2a94bfd33", "Host": "httpbin.org", "User-Agent": "python-requests/2.22.0" }, "json": null, "origin": "117.223.63.135, 117.223.63.135", "url": "https://httpbin.org/post" }
🌐
Requests
requests.readthedocs.io › en › latest › user › quickstart
Quickstart — Requests 2.33.0.dev1 documentation
Note, the json parameter is ignored if either data or files is passed. Requests makes it simple to upload Multipart-encoded files:
Find elsewhere
🌐
Omeka
forum.omeka.org › omeka classic › development
File upload using REST API and Python requests - Development - Omeka Forum
February 21, 2020 - Hi, I ran into an issue uploading a file to an Omeka Classic instance using Python requests. I tried to use code examples from here: Those examples are for Omeka S, so I modified my code in terms of credentials, so my version looks like this: params = { 'key': api_key } data = { "o:ingester": "upload", "file_index": "0", "o:item": {"o:id": item_id} } files = [ ('data', (None, json.dumps(data), 'application/json')), ('file[0]', ('my_picture.jpg', open('my_pictur...
🌐
ProxiesAPI
proxiesapi.com › articles › a-beginner-s-guide-to-uploading-files-with-python-requests
A Beginner's Guide to Uploading Files with Python Requests | ProxiesAPI
Requests is a Python library for making HTTP requests, including file uploads. It simplifies the process and provides features like automatic JSON encoding and decoding. This guide walks through the steps for uploading single and multiple files, as well as additional options and error handling.
Top answer
1 of 9
427

If upload_file is meant to be the file, use:

files = {'upload_file': open('file.txt','rb')}
values = {'DB': 'photcat', 'OUT': 'csv', 'SHORT': 'short'}

r = requests.post(url, files=files, data=values)

and requests will send a multi-part form POST body with the upload_file field set to the contents of the file.txt file.

The filename will be included in the mime header for the specific field:

>>> import requests
>>> open('file.txt', 'wb')  # create an empty demo file
<_io.BufferedWriter name='file.txt'>
>>> files = {'upload_file': open('file.txt', 'rb')}
>>> print(requests.Request('POST', 'http://example.com', files=files).prepare().body.decode('ascii'))
--c226ce13d09842658ffbd31e0563c6bd
Content-Disposition: form-data; name="upload_file"; filename="file.txt"


--c226ce13d09842658ffbd31e0563c6bd--

Note the filename="file.txt" parameter.

You can use a tuple for the files mapping value, with between 2 and 4 elements, if you need more control. The first element is the filename, followed by the contents, and an optional content-type header value and an optional mapping of additional headers:

files = {'upload_file': ('foobar.txt', open('file.txt','rb'), 'text/x-spam')}

This sets an alternative filename and content type, leaving out the optional headers.

If you are meaning the whole POST body to be taken from a file (with no other fields specified), then don't use the files parameter, just post the file directly as data. You then may want to set a Content-Type header too, as none will be set otherwise. See Python requests - POST data from a file.

2 of 9
64

The new Python requests library has simplified this process, we can use the 'files' variable to signal that we want to upload a multipart-encoded file:

url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}

r = requests.post(url, files=files)
r.text
🌐
GitHub
github.com › psf › requests › issues › 3842
PUT (requests.put) specifying the source file location for zip file error 10054 · Issue #3842 · psf/requests
January 31, 2017 - C:\svn\libraries\cpp>python req_put.py default.zip Traceback (most recent call last): File "req_put.py", line 102, in <module> resp = requests.put(uri, headers=headers, data=data) # data=data , params=payload) File "C:\Python27\lib\site-pac...
Author   Twoflower2
🌐
Sensible
sensible.so › blog › python-upload-files
Six Methods to Upload Files in Python | Sensible Blog
You can use the requests library to upload multiple files to any API endpoint in the same request. Save the following code in a file named requests-test.py in a new directory named multiple and run the command python3 requests-test.py in a new terminal window inside the multiple folder:
🌐
TechBullion
techbullion.com › home › how to upload files using python requests
How to Upload Files Using Python Requests - TechBullion
August 22, 2022 - The post() method signature and the requests library will be discussed first in the article. The procedure for utilizing the requests package to upload a single file will next be discussed.
🌐
Apidog
apidog.com › blog › python-put-request
How to make a PUT Request in Python (2026 Guide)
February 2, 2026 - This library allows you to send HTTP/1.1 requests extremely easily. In Python, you can make a PUT request using the requests library, which is a popular HTTP library for making HTTP requests.
🌐
ReqBin
reqbin.com › code › python › 6mwlgbqa › python-requests-download-file-example
How do I download a file using Python Requests?
To download a file using the Python Request library, you need to make a GET, POST, or PUT request and read the server's response data using response.content, response.json, or response.raw objects, and then save it to disk using the Python file object methods.
🌐
GitHub
github.com › psf › requests › issues › 5653
Help Needed: Uploading tarfile using python requests library's post · Issue #5653 · psf/requests
November 11, 2020 - import requests data = {'file':open('tgz_file.tgz')} headers = {'x-auth-token': 'some_token', 'Accept': 'application/json', 'Content-Type': 'multipart/form-data'} requests.post(url=https://<some_server>/api/url, headers=headers, data=data) ... Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python3.6/site-packages/requests/api.py", line 112, in post return request('post', url, data=data, json=json, **kwargs) File "/usr/lib/python3.6/site-packages/requests/api.py", line 58, in request return session.request(method=method, url=url, **kwargs) File "/usr/lib/p
Author   moijes12
🌐
Stack Overflow
stackoverflow.com › questions › 70868660 › python-put-requests-a-file
python put requests a file - Stack Overflow
url = "https://some_website.com" auth_token = "Bearer auth tokenp089u098u08j98jasdfsadgfasdg" headers = {"Content-Type": "multipart/form-data", "Accept": "*/*", "Authorization": sa_token} file_loc = "C:/location/of/file/I/want/to/put/Capture.JPG" metadata = { "docType":"doc_file", "docTypeNamespace": "platform", "fileType":"IMAGE", "docReferences": { "name": "this is the form to confirm receipt" }, "identifiers": { "consignment": { "carrierBookingNumber":"9876smg", "billOfLadingNumber":"1234smg" } } } body = { "file": {}, "metadata": metadata } resp = requests.put(url=url, headers=headers, data=body)
🌐
Java Code Geeks
examples.javacodegeeks.com › home › web development › python
Upload Files with Python's Requests Library - Examples Java Code Geeks
June 7, 2021 - Hello in this tutorial, we will see how to upload a file using the requests library in Python. We will cover the HTTP POST method to upload the files to a