Concept Flow - Secure filename handling
User uploads file
Extract filename
Sanitize filename
Save file with safe name
Return success or error
This flow shows how Flask handles uploaded filenames safely by cleaning them before saving.
from flask import Flask, request from werkzeug.utils import secure_filename filename = secure_filename(request.files['file'].filename)
| Step | Action | Input Filename | Sanitized Filename | Reason |
|---|---|---|---|---|
| 1 | Receive file upload | my photo.png | User uploads a file with spaces | |
| 2 | Call secure_filename() | my photo.png | my_photo.png | Spaces replaced with underscores |
| 3 | Check for unsafe chars | my_photo.png | my_photo.png | No unsafe chars found |
| 4 | Return sanitized filename | my_photo.png | Ready to save safely | |
| 5 | Save file | my_photo.png | File saved with safe name | |
| 6 | End | Process complete |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| filename | my photo.png | my_photo.png | my_photo.png | my_photo.png |
Use werkzeug.utils.secure_filename(filename) to clean filenames. It replaces spaces with underscores and removes unsafe characters. Prevents path traversal attacks by stripping dangerous parts. Always sanitize filenames before saving uploaded files. Ensures files save safely in your server folder.