Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 72 ยท Forms and User Input

File Uploads

Accept file uploads in Flask safely: read request.files, clean names with secure_filename, cap size with MAX_CONTENT_LENGTH, check types and choose storage.

Letting users upload a file looks easy: the browser sends the bytes, Flask hands you an object, you call .save(). It is also one of the riskiest features in a web app, because the user controls the file name, the size, the declared type and the content. This lesson shows the mechanics first and then the checks that make an upload endpoint safe.

You will receive files through request.files (see The Request Object), clean the file name, enforce a size limit, verify the type, and choose where the bytes go. The examples run in the browser with in-memory files, so nothing touches a disk; the lesson marks the one part that does as read-only.

The HTML side

A form can only send files if it uses method="post" and enctype="multipart/form-data". Without that encoding the browser sends just the file name, not the file:

HTML
<form method="post" action="/upload" enctype="multipart/form-data">
  <input type="file" name="avatar" accept="image/png,image/jpeg">
  <button>Upload</button>
</form>

The accept attribute is only a hint for the file picker. A user can bypass it with one line of curl, so the server must check everything itself.

request.files and FileStorage

Each uploaded file arrives as a FileStorage object, collected in request.files, which behaves like a dictionary keyed by the field name. Useful attributes:

  • filename: the name the client claims (never trust it).
  • content_type / mimetype: the type the client claims (never trust it either).
  • stream, read(), save(dst): access to the bytes.

The test client can build a multipart request from a (BytesIO, filename) tuple, so no real file is needed:

Python Receive a file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice the file.filename == "" check: when the user presses Upload without choosing anything, browsers still send the field, with an empty name. Always handle that case.

Never trust the file name

A client can send a name like ../../app.py or C:\Windows\evil.exe. If you join that to your upload folder and save, the file may land outside it (a path traversal attack). Werkzeug's secure_filename() reduces a name to a safe ASCII version: it drops directory parts, replaces spaces with underscores and strips unusual characters.

Python secure_filename in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two details matter. First, the result can be an empty string (for example when the name was all unusual characters), so test for that. Second, secure_filename does not make names unique: two users uploading photo.jpg would overwrite each other. A common fix is to ignore the client name for storage and generate your own, such as uuid.uuid4().hex + ".jpg", keeping the original only as display text in your database.

Limiting the size

Without a limit, someone can upload gigabytes and fill your disk or memory. Set MAX_CONTENT_LENGTH (in bytes) in the config. When a request body is larger, Flask stops reading and responds with 413 Request Entity Too Large:

Python MAX_CONTENT_LENGTH and 413

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Registering a 413 handler (see Error handling) lets you return a friendly message instead of the default page. The limit applies to the whole request, so leave room for form fields and multipart overhead. A web server in front of Flask (nginx's client_max_body_size, for instance) should enforce a similar cap so oversized bodies are rejected before they reach Python.

Here is how the checks stack up on a request:

flowchart TD
    A["Browser sends multipart request"] --> B{"Body larger than<br/>MAX_CONTENT_LENGTH?"}
    B -- yes --> C["413 Request Entity Too Large"]
    B -- no --> D{"File present and<br/>filename not empty?"}
    D -- no --> E["400 no file"]
    D -- yes --> F{"Extension allowed?<br/>Content looks right?"}
    F -- no --> G["400 / 415 rejected"]
    F -- yes --> H["Generate safe name<br/>and store the bytes"]

Reject early and cheaply; only a file that passes every check is stored.

Checking the type

The Content-Type of a part is just a header the client wrote. Layer a few checks:

  1. Extension allow-list. Compare the lowercased extension against a fixed set such as {"png", "jpg", "jpeg"}. Use an allow-list, never a block-list.
  2. Content check. Look at the first bytes. A PNG always begins with the eight bytes \x89PNG\r\n\x1a\n. Libraries such as Pillow can go further by actually opening the image.
  3. Serve safely. Uploaded files must never be executed or served with a guessed type. Serve them as downloads or from a separate domain or bucket.

The next example combines these checks and "stores" files in a dictionary, a stand-in for a disk folder:

Python A validated upload endpoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Only the real PNG and the traversal attempt (cleaned to notes.txt) end up stored. The fake PNG is caught by the signature check, and the .py file by the allow-list.

Where the bytes go (read-only)

On a real server, file.save() writes to disk. Build the path from a folder you control and a name you generated or cleaned:

Python
import os

UPLOAD_DIR = os.path.join(app.instance_path, "uploads")
os.makedirs(UPLOAD_DIR, exist_ok=True)

file.save(os.path.join(UPLOAD_DIR, stored_name))

This cannot run in the browser sandbox, but the shape is the same as the dictionary version above. Some practical guidance:

  • Keep uploads outside the static folder unless you really intend to publish them, and never inside the code directory.
  • For anything beyond a small site, store files in object storage (S3 or similar) and keep only the key in your database.
  • To send a stored file back, use send_from_directory(UPLOAD_DIR, name), which refuses paths that escape the folder (see Static files).
  • Large uploads streamed through Python tie up a worker. Consider direct-to-storage uploads with signed URLs for big files.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which form attribute is required for the browser to send file contents?

    Without multipart encoding the browser submits only the file's name. The accept attribute is just a hint for the picker.
  2. 2. What does secure_filename("../../app.py") protect against, and what does it NOT do?

    It strips directory parts and odd characters. Uniqueness, type checks and size limits are your job.
  3. 3. What status does Flask return when the body exceeds MAX_CONTENT_LENGTH?

    Flask stops reading the body and answers 413. You can customize the response with @app.errorhandler(413).
  4. 4. Why is file.content_type == "image/png" not enough to prove a file is a PNG?

    Check the extension against an allow-list and inspect the real bytes (such as the PNG signature) instead.
  5. 5. A user submits the upload form without choosing a file. What does your view typically see?

    Browsers send the field with an empty name, so check file.filename == "".

Summary

  • Forms need method="post" and enctype="multipart/form-data"; files appear in request.files as FileStorage objects.
  • The file name, content type and accept attribute all come from the client: treat them as untrusted.
  • Clean names with secure_filename(), handle an empty result, and prefer generating your own storage names.
  • Set MAX_CONTENT_LENGTH to get a 413 for oversized requests, and repeat the cap in your web server.
  • Validate with an extension allow-list plus a check of the actual bytes.
  • Save outside static, build paths from a trusted folder, and use object storage as the site grows.

Next: Cookies, how small pieces of state travel between the browser and your app.