0
0
PythonHow-ToBeginner · 3 min read

How to Upload File Using Python Requests: Simple Guide

To upload a file using python requests, use the files parameter in requests.post() with a dictionary containing the file name and file object. This sends the file as multipart/form-data to the server.
📐

Syntax

Use requests.post() with the files argument to upload files. The files argument expects a dictionary where the key is the form field name and the value is a tuple with the file name and the file object.

  • requests.post(url, files=files_dict): Sends a POST request to url with files.
  • files_dict: Dictionary like {'fieldname': ('filename', file_object)}.
  • file_object: Open the file in binary mode 'rb' to read it.
python
import requests

url = 'http://example.com/upload'
files = {'file': ('example.txt', open('example.txt', 'rb'))}
response = requests.post(url, files=files)
print(response.status_code)
💻

Example

This example uploads a local file named example.txt to a test server that accepts file uploads. It prints the server response status code to confirm success.

python
import requests

url = 'https://httpbin.org/post'

# Open the file in binary mode
with open('example.txt', 'rb') as f:
    files = {'file': ('example.txt', f)}
    response = requests.post(url, files=files)

print('Status code:', response.status_code)
print('Response JSON:', response.json()['files'])
Output
Status code: 200 Response JSON: {'file': 'Content of example.txt here...'}
⚠️

Common Pitfalls

  • Not opening the file in binary mode 'rb' can cause errors or corrupted uploads.
  • Forgetting to close the file can lead to resource leaks; use with statement to handle this automatically.
  • Passing file path string instead of file object to files will not work.
  • Not using the correct form field name expected by the server can cause upload failure.
python
import requests

url = 'https://httpbin.org/post'

# Wrong: passing file path string instead of file object
files_wrong = {'file': 'example.txt'}

# Correct: open file in binary mode
with open('example.txt', 'rb') as f:
    files_correct = {'file': ('example.txt', f)}
    response = requests.post(url, files=files_correct)
    print('Status code:', response.status_code)
Output
Status code: 200
📊

Quick Reference

Remember these key points when uploading files with requests:

  • Use files={'fieldname': ('filename', open('file', 'rb'))}
  • Always open files in binary mode 'rb'
  • Use with to auto-close files
  • Check server's expected form field name
  • Inspect response status code for success (usually 200)

Key Takeaways

Use the files parameter in requests.post() with a dictionary of form field name and file tuple.
Always open files in binary mode ('rb') to upload correctly.
Use the with statement to ensure files are properly closed after uploading.
Check the server's expected form field name to avoid upload errors.
Verify the response status code to confirm successful upload.