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.

Answer from Martijn Pieters on Stack Overflow
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
🌐
Sensible
sensible.so › blog › python-upload-files
Six Methods to Upload Files in Python | Sensible Blog
In this section, you'll use a few different methods to upload a single file in Python: the requests library, the ftplib module, the Filestack API, and a Django web app.
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
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
Help Needed: Uploading tarfile using python requests library's post
I am trying to upload tgz files to a server using the python requests library. I am not sure how to pass the files to be uploaded. The curl command that I have to convert into a python request is a... More on github.com
🌐 github.com
3
November 11, 2020
Rest API: Upload file with Python
I upload an image using Rest API with python. It response 200 and fileURL. The folder was created but the image was not created. I tried curl, it works fine. Have any idea? More on support.backendless.com
🌐 support.backendless.com
1
0
February 12, 2016
🌐
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.
🌐
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.
🌐
Stack Abuse
stackabuse.com › how-to-upload-files-with-pythons-requests-library
How to Upload Files with Python's requests Library
September 19, 2021 - Good job! You can upload single and multiple files with requests! In this article, we learned how to upload files in Python using the requests library. Where it's a single file or multiple files, only a few tweaks are needed with the post() method.
🌐
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': ('test1.txt', 'Welcome to TutorialsPoint')} getdata = requests.post(myurl, files=files) print(getdata.text) E:\prequests>python makeRequest.py { "args": {}, "data": "", "files": { "file": "Welcome to TutorialsPoint" }, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "170", "Content-Type": "multipart/form-data; boundary=f2837238286fe40e32080aa7e172be4f", "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" }
Find elsewhere
🌐
ProxiesAPI
proxiesapi.com › articles › uploading-files-in-python-requests-a-guide
Uploading Files in Python Requests: A Guide | ProxiesAPI
Simply add additional key/value pairs to the files dictionary: ... files = { 'file1': open('photo.jpg', 'rb'), 'file2': open('document.pdf', 'rb') } r = requests.post(url, files=files)
🌐
Java Code Geeks
examples.javacodegeeks.com › home › web development › python
Upload Files with Python's Requests Library - Examples Java Code Geeks
June 7, 2021 - Add the following code to the python script. The script consists of a dictionary object to hold multiple names and files. Once the file list is ready we will send the HTTP POST request to a free bin service that can simulate the post-operation and return an HTTP response. The dummy files (named – file1.txt and file2.txt) used in this script can be download from the Downloads section. ... # Upload file using python requests library # import module import requests # url - http://httpbin.org/ # making use of a free httpbin service post_url = 'http://httpbin.org/post' # method to upload files de
🌐
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...
🌐
IBM
ibm.com › support › pages › how-use-python-requests-library-uploading-file-using-watson-studio-local-1231-filemgmt-api
How to use Python requests library for uploading file using Watson Studio Local 1.2.3.1 filemgmt API
December 30, 2019 - import requests import json url = 'https://wsl-server.company.org/v1/preauth/validateAuth' r = requests.get(url,auth=('dsxuser02', 'Pass1234'), verify=False) res = r.json() bearerToken=res["accessToken"] header = {'Authorization': 'Bearer {}'.format(bearerToken)} url = 'https://wsl-server.company.org/api/v1/filemgmt/user-home' files = {'file': ('aaa.csv', open('aaa.csv', 'rb'),'text/csv')} r = requests.post(url, headers=header, files=files, verify=False) r.text · Which give following result: # python filemgmt_upload.py {"success":true,"result":"aaa.csv (16 Bytes) uploaded\n"} [{"Business Unit
🌐
FastAPI
fastapi.tiangolo.com › tutorial › request-files
Request Files - FastAPI
You can declare multiple File and Form parameters in a path operation, but you can't also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json. This is not a limitation of FastAPI, it's part of the HTTP protocol. You can make a file optional by using standard type annotations and setting a default value of None: ... from typing import Annotated from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") async def create_file(file: Annotated[bytes | None, File()] = None): if not file: return {"message": "No file sent"} else: return {"file_size": len(file)} @app.post("/uploadfile/") async def create_upload_file(file: UploadFile | None = None): if not file: return {"message": "No upload file sent"} else: return {"filename": file.filename}
🌐
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
🌐
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.
🌐
Stack Abuse
stackabuse.com › bytes › how-to-send-multipart-form-data-with-requests-in-python
How to Send "multipart/form-data" with Requests in Python
January 29, 2025 - A status code of 200 means the request was successful. Note: Make sure to replace 'http://example.com/upload' with the actual URL you want to send the file to, and '/path/to/your/file.jpg' with the actual path of the file you want to upload before running this code. When working with multipart/form-data and Python requests, there are a few potential errors you should check for and handle.
🌐
Backendless
support.backendless.com › general
Rest API: Upload file with Python - General - Backendless Support
February 12, 2016 - I upload an image using Rest API with python. It response 200 and fileURL. The folder was created but the image was not created. I tried curl, it works fine. Have any idea?
🌐
Medium
medium.com › @API4AI › post-a-file-via-http-request-the-ultimate-guide-b23fb70a3f73
POST a File via HTTP Request | The Ultimate Guide | by API4AI | Medium
February 23, 2024 - Both snippets demonstrate the straightforward yet powerful way Python can interact with APIs to upload files. While Requests offers simplicity, AIOHTTP brings the added advantage of asynchronous operations, making it suitable for scenarios with high I/O operations or when building asynchronous applications.
🌐
Gabriele Romanato
gabrieleromanato.name › python-how-to-upload-files-with-the-requests-module
Python: how to upload files with the requests module | Gabriele Romanato
January 29, 2023 - import os import requests def upload_file(url, file_path): if not os.path.exists(file_path): return False with open(file_path, 'rb') as f: files = {'file': f} try: r = requests.post(url, files=files) except requests.exceptions.RequestException: return False return True
Top answer
1 of 2
14

A few points :

  • make sure to submit your request to the correct url ( the form 'action' )
  • use the data parameter to submit other form fields ( 'dir', 'submit' )
  • include the name of the file in files ( this is optional )

code :

import requests

url = 'http://example.com' + '/upload.php'
data = {'dir':'/uploads/', 'submit':'Submit'}
files = {'file':('1.jpg', open('1.jpg', 'rb'))}
r = requests.post(url, data=data, files=files)

print(r.content)
2 of 2
3

First of all, define path of upload directory like,

app.config['UPLOAD_FOLDER'] = 'uploads/'

Then define file extension which allowed to upload like,

app.config['ALLOWED_EXTENSIONS'] = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

Now suppose you call function to process upload file then you have to write code something like this,

# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
    # Get the name of the uploaded file
    file = request.files['file']

    # Check if the file is one of the allowed types/extensions
    if file and allowed_file(file.filename):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)

        # Move the file form the temporal folder to
        # the upload folder we setup
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

        # Redirect the user to the uploaded_file route, which
        # will basicaly show on the browser the uploaded file
        return redirect(url_for('YOUR REDIRECT FUNCTION NAME',filename=filename))

This way you can upload your file and store it in your located folder.

I hope this will help you.

Thanks.