Back to all snippets
Library/Python/File Upload Script
pythonintermediatefilesuploadrequestshttp

How to implement File Upload Script in Python

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.

Code Snippet

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

What is File Upload Script?

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.

How It Works

  1. 1Open the file in binary mode: `open(filename, 'rb')`
  2. 2Pass to `requests.post(url, files={'field_name': f})`
  3. 3`requests` sets the correct Content-Type and encoding
  4. 4Server receives the file in a form field

Common Use Cases

  • Image uploads - Upload profile pictures, avatars
  • Document submission - Submit resumes, invoices
  • Backup scripts - Upload data to cloud storage
  • Bulk data import - Upload CSV files for processing

Key Benefits

  • No manual multipart encoding needed
  • Works with any server that accepts multipart uploads
  • Simple one-liner for most cases
  • Supports progress bars and callbacks

Common Mistakes to Avoid

  • Opening file in text mode instead of binary — always use `'rb'` (read binary). Text mode corrupts binary files.
  • Not closing the file — use `with open()` or `f.close()` to release the file handle.
  • Not checking response status — always verify the upload succeeded before moving on.

Quick Tips

  • Click the "Copy" button above to copy the code to your clipboard
  • This code is production-ready and can be used in your projects immediately
  • Check out related snippets below for more python examples

Frequently Asked Questions

How do I upload multiple files?

Pass a list of tuples: `files=[('file', open('file1.txt', 'rb')), ('file', open('file2.txt', 'rb'))]`.

How do I show upload progress?

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.

About This Python Code Snippet

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.

Tags: files, upload, requests, http  | Language: python  | Difficulty: intermediate  | Category: Python

Build Your Own Snippet Library

Organise your team's code snippets with Snippetly. Share knowledge and boost productivity across your organisation.