Upload files to a server or cloud storage in Python
Quick Answer
Open the file in binary mode and pass it to `requests.post()` with `files={'field': open(..., 'rb')}`—requests handles multipart encoding automatically.
1import requests
2import os
3from typing import Optional
4
5# Simple file upload
6def upload_file(filepath: str, server_url: str) -> bool:
7 try:
8 with open(filepath, 'rb') as f:
9 files = {'file': f}
10 response = requests.post(server_url, files=files, timeout=10)
11
12 return response.status_code == 200
13 except Exception as e:
14 print(f"Upload failed: {e}")
15 return False
16
17upload_file('document.pdf', 'https://example.com/upload')
18
19# Upload with metadata
20def upload_with_metadata(filepath: str, server_url: str, title: str, description: str) -> bool:
21 with open(filepath, 'rb') as f:
22 files = {'file': f}
23 data = {'title': title, 'description': description}
24 response = requests.post(server_url, files=files, data=data)
25
26 return response.status_code == 200
27
28# Multiple file upload
29def upload_multiple(filepaths: list[str], server_url: str) -> bool:
30 files = []
31 for filepath in filepaths:
32 f = open(filepath, 'rb')
33 files.append(('files', f))
34
35 try:
36 response = requests.post(server_url, files=files)
37 return response.status_code == 200
38 finally:
39 for _, f in files:
40 f.close()Uploading files requires multipart/form-data encoding. The `requests` library handles all the complexity automatically — you just open the file and pass it to `files` parameter. This snippet covers basic uploads, progress bars, and error handling.
Pass a list of tuples: `files=[('file', open('file1.txt', 'rb')), ('file', open('file2.txt', 'rb'))]`.
Use `tqdm` library with `requests-toolbelt` for chunked uploads with progress bars: `from requests_toolbelt import MultipartEncoder; progress = tqdm.tqdm(total=file_size)` then update on each chunk.
This free python code snippet for file upload script is production-ready and copy-paste friendly. Whether you are building a web app, API, or frontend interface, this intermediate-level example will help you implement file upload script quickly and correctly.
All snippets in the Snippetly library follow python best practices and are tested for real-world use. You can adapt this code to work with React, Vue, Node.js, or any project that uses python.
Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.