$ pip install filestack-pythonclient = Client('YOUR_API_KEY')
filelink = client.upload(filepath='path/to/report.pdf')
print(filelink.url)
Python File Upload at a Glance
Python file upload means either sending a file from Python, usually with the requests library and multipart/form-data, or accepting uploaded files in a web framework such as Flask, Django or FastAPI. The Filestack Python SDK (pip install filestack-python) covers both, uploading from a path, file object or URL with resumable multipart uploads, cloud storage and transformations included.
Send a file from a script
- Path, file or URL On disk or on the web
-
client.upload()Multipart, with retries - Filelink Handle and CDN URL
Accept a file in a web app
- Django, Flask, FastAPI The request's file
-
file_obj=With name and type - Cloud storage Filestack or your S3
- Package
filestack-python, installed with pip or Poetry- Python
- Python 3; PyPI lists 3.7 through 3.12
- Upload from
- A path, a file object, or a URL with
upload_url() - Filelinks
- Download, overwrite, delete and transform any uploaded file
- Large files
- Multipart uploads, and Intelligent Ingestion with
intelligent=Trueon paid plans - Security
- Signed policies with
Security, and webhook verification withverify_webhook_signature() - Storage
- Filestack storage, or your own Amazon S3, Google Cloud Storage or Azure container
- Getting started
- Free plan with an API key. Compare plans
Upload a File From Python
To upload a file to an API with Python requests, open it in binary mode and pass it in files=, which sends multipart/form-data. To upload to cloud storage instead, call client.upload() from filestack-python.
With Python requests, upload a file by passing it open in binary mode to
files=. In Python, upload a file to a server this way for any multipart endpoint, or usedata=for APIs that take raw bytes.client.upload()stores the file and returns a Filelink with its handle and CDN URL.upload_url()stores a file Filestack fetches from a public URL. The URL upload guide covers it step by step.Loop over the files and retry each one with a backoff, so one slow upload is retried on its own.
with open('report.pdf', 'rb') as f:
response = requests.post(
'https:/
files={'file': ('report.pdf', f, 'application/pdf')},
timeout=30,
)
response.raise_for_status()
client = Client('YOUR_API_KEY')
filelink = client.upload(filepath='report.pdf')
print(filelink.handle)
print(filelink.url)
print(filelink.url)
def upload_with_retry(path, attempts=3):
for attempt in range(1, attempts + 1):
try:
return client.upload(filepath=path)
except Exception:
if attempt == attempts:
raise
time.sleep(2 ** attempt)
for path in ['invoice-001.pdf', 'invoice-002.pdf']:
print(path, upload_with_retry(path).handle)
Accept File Uploads in Django, Flask and FastAPI
To handle file uploads in Django, Flask or FastAPI, read the uploaded file from the request, then pass its file object to client.upload() with the original name and type.
Django puts uploaded files in
request.FILES.Flask puts uploaded files in
request.files, andMAX_CONTENT_LENGTHcaps the request size.FastAPI passes an
UploadFile. A plaindefroute runs the upload in a worker thread.
from django.views.decorators.http import require_POST
from filestack import Client
client = Client('YOUR_API_KEY')
@require_POST
def upload(request):
f = request.FILES['file']
filelink = client.upload(file_obj=f, store_params={
'filename': f.name, 'mimetype': f.content_type})
return JsonResponse({'handle': filelink.handle, 'url': filelink.url})
from werkzeug.utils import secure_filename
from filestack import Client
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
client = Client('YOUR_API_KEY')
@app.post('/upload')
def upload():
f = request.files['file']
filelink = client.upload(file_obj=f.stream, store_params={
'filename': secure_filename(f.filename), 'mimetype': f.mimetype})
return {'handle': filelink.handle, 'url': filelink.url}
from filestack import Client
app = FastAPI()
client = Client('YOUR_API_KEY')
@app.post('/upload')
def upload(file: UploadFile):
filelink = client.upload(file_obj=file.file, store_params={
'filename': file.filename, 'mimetype': file.content_type})
return {'handle': filelink.handle, 'url': filelink.url}
For large files, upload from the browser with File Picker. Files go straight to storage, your view receives the handle, and Python workers stay free for application requests.
Large Files With Resumable Python Multipart Upload
The best way to upload large files from Python is a resumable multipart upload. The file is split into chunks, the chunks upload in parallel, and a failed chunk is retried on its own.
filestack-python uploads in chunks by default. With intelligent=True, Intelligent Ingestion adapts chunk size to the network, on paid plans. How resumable uploads work
client = Client('YOUR_API_KEY')
filelink = client.upload(
filepath='path/to/archive.zip',
intelligent=True,
)
print(filelink.handle)
Process Files After Upload
To generate thumbnails after upload, chain resize() on the Filelink and call store(). To extract text from uploaded PDFs, run OCR in a Workflow and read the result from a signed webhook.
Chain image tasks on a Filelink, then
store()saves the result as a new file.Attach a Workflow to the upload, and it runs OCR, conversion or virus detection as the file arrives. OCR runs on paid plans.
Filestack signs every webhook with
FS-Signature.verify_webhook_signature()checks it against the raw body before your app trusts the result. Webhooks run on paid plans.
.filetype_conversion(format='webp') \
.store()
print(thumb.url)
filepath='invoice.pdf',
store_params={'workflows': ['YOUR_WORKFLOW_ID']},
)
from filestack.helpers import verify_webhook_signature
app = Flask(__name__)
@app.post('/filestack')
def filestack_webhook():
valid, details = verify_webhook_signature(
'YOUR_WEBHOOK_SECRET', request.get_data(), {
'FS-Signature': request.headers['FS-Signature'],
'FS-Timestamp': request.headers['FS-Timestamp']})
if not valid:
abort(401)
return '', 200
Upload to Your Own S3 Bucket
To upload a file to S3 from Python, use boto3 for a direct write to your own bucket, or connect the bucket in the Filestack developer portal and set location in store_params.
boto3, direct to S3
One call writes the file to your bucket.
s3 = boto3.client('s3')
s3.upload_file('report.pdf', 'my-bucket', 'uploads/report.pdf')
Filestack, into your bucket
The same write, with a handle, CDN URL and transformations on the result.
filepath='report.pdf',
store_params={'location': 's3', 'path': 'uploads/'},
)
| boto3 | Filestack | |
|---|---|---|
| Destination | Your S3 bucket | Your S3 bucket, GCS, Azure or Filestack storage |
| Large files | Managed multipart transfers | Multipart, and Intelligent Ingestion on paid plans |
| Browser uploads | Presigned URLs you generate | File Picker with cloud sources |
| Scanning and processing | Services you add | Virus detection, OCR and transformations |
Secure Python File Uploads
Block malicious files during upload by checking content rather than the extension, capping size, cleaning file names, scanning every file and signing every request.
-
Check the content
Python 3.13 removed
imghdr. Check file type with python-magic, or in File Picker withacceptFn. -
Cap the size
Set
MAX_CONTENT_LENGTHin Flask orDATA_UPLOAD_MAX_MEMORY_SIZEin Django. -
Clean file names
Run names through
secure_filename(). Filestack stores each file under a unique handle. -
Scan for viruses
Virus detection runs in Workflows on any file type, on paid plans.
-
Sign every request
A
Securityobject signs a policy with your app secret. The client applies it to every call it makes.
from filestack import Client, Security
policy = {'expiry': int(time.time()) + 3600, 'call': ['store']}
security = Security(policy, 'YOUR_APP_SECRET')
client = Client('YOUR_API_KEY', security=security)
filelink = client.upload(filepath='path/to/file.pdf')
Which Python Upload Method Should You Use?
Use requests to post to an API you run, boto3 to write straight to S3, your framework’s handler to accept user files, and the Filestack SDK for upload, storage, resume, scanning and processing in one client.
| requests to your API | boto3 to S3 | Framework handler | Filestack SDK | |
|---|---|---|---|---|
| Setup | An API that receives files | An S3 bucket and IAM credentials | A view or route | An API key |
| Large files | Your API's limits | Managed multipart transfers | Server and worker limits | Multipart uploads |
| Resume | Custom code | Multipart retries | Custom code | Intelligent Ingestion on paid plans |
| Scanning | Your own scanner | Your own scanner | Your own scanner | Virus detection on paid plans |
| Processing | Your own code | Services you add | Your own code | Transformations, conversion and OCR |
| Best for | Sending files to a service you own | Teams running AWS directly | Small apps with light uploads | Teams that want uploads handled end to end |
boto3 suits teams that already run AWS and want files written straight to S3.
Python file upload, done.
- Most teams ship their first upload in under a day
- Trusted by 100,000+ applications
- SOC 2 compliant
Python File Upload FAQs
How do I upload a file in Python?
Open the file in binary mode and send it with requests.post(url, files={'file': f}), or call client.upload(filepath='file.pdf') from filestack-python to store it in the cloud and get a CDN URL.
How do I upload a file with Python requests?
Pass the open file in the files argument: requests.post(url, files={'file': ('name.pdf', f, 'application/pdf')}). requests builds the multipart/form-data body and sets the boundary header.
How do I upload a file to a server from Python?
POST it as multipart/form-data with requests to the server’s upload endpoint, and call raise_for_status() to confirm it arrived. To upload to cloud storage, use client.upload() from filestack-python.
How do I handle file uploads in Django or Flask?
Read the file from request.FILES in Django or request.files in Flask, then pass its file object to client.upload() with the filename and MIME type in store_params.
How do I upload large files in Python?
Use a multipart upload that splits the file into chunks and retries each one. filestack-python uploads in chunks by default, and intelligent=True adds Intelligent Ingestion on paid plans.
Which Python versions does the Filestack SDK support?
filestack-python runs on Python 3, and its PyPI package lists Python 3.7 through 3.12.