File Uploads (Flask)

File uploads in Flask are accessed through request.files, which holds files submitted by a multipart form. You read a file, validate it, sanitize its name with secure_filename(), and save it with file.save(path).

Flask

To accept uploads the HTML form needs enctype='multipart/form-data' and a file input. On the server, request.files['photo'] gives you a FileStorage object with the original filename, content type, and a stream you can save.

Security matters here: always pass the filename through werkzeug's secure_filename() to strip dangerous path components before saving, restrict allowed extensions, and set MAX_CONTENT_LENGTH in config to cap upload size and prevent denial-of-service via huge files.

Store uploads outside your static/ code folder (a dedicated media/ or uploads/ directory), and never trust the client-provided content type when deciding how to handle a file.

Syntax

f = request.files["photo"]
f.save(path)

Examples

Python

from werkzeug.utils import secure_filename
import os

@app.route("/upload", methods=["POST"])
def upload():
    f = request.files["photo"]
    name = secure_filename(f.filename)
    f.save(os.path.join("uploads", name))
    return f"Saved {name}"

Learn it in a lesson

See also

Back to the Dictionary