File Uploading
File upload forms require a different encoding.
flowchart TD
A["form enctype='multipart/form-data'"] --> B{"set?"}
B -->|no| C["fields arrive in request.form, request.files is EMPTY"]
B -->|yes| D["browser sends the file parts"]
D --> E{"body under MAX_CONTENT_LENGTH?"}
E -->|no| F["413 Request Entity Too Large -- your view never runs"]
E -->|yes| G["request.files['field_name']"]
G --> H{"a file was actually chosen?"}
H -->|no| I["an empty FileStorage with filename '' -- check for it"]
H -->|yes| J["secure_filename, validate, then save"]
HTML form
Section titled “HTML form”<form method="post" enctype="multipart/form-data">
<input type="file" name="photo" />
<button type="submit">Upload</button>
</form>Flask route
Section titled “Flask route”from flask import Flask, request
app = Flask(__name__)
@app.route("/upload", methods=["GET", "POST"])
def upload():
if request.method == "POST":
file = request.files.get("photo")
if not file:
return "No file uploaded", 400
# saving comes next (see secure filenames)
return "File received", 200
return "Upload form"Why request.form doesn’t contain files
Section titled “Why request.form doesn’t contain files”Files are streamed separately and exposed via:
request.files
Common pitfalls
Section titled “Common pitfalls”- Forgetting
enctype="multipart/form-data"→ files missing - Not setting size limits
- Accepting any file type blindly
In a real app, validate:
- allowed file extensions
- MIME type
- file size
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading