0
0
Flaskframework~5 mins

Secure filename handling in Flask

Choose your learning style9 modes available
Introduction

When users upload files, their filenames might contain unsafe characters or paths. Secure filename handling makes sure these names are safe to use on your server.

When accepting file uploads from users on a website.
When saving files to your server to avoid overwriting or security risks.
When you want to prevent directory traversal attacks through filenames.
When you need to ensure filenames are valid and safe for your operating system.
Syntax
Flask
from werkzeug.utils import secure_filename

filename = secure_filename(user_uploaded_filename)

secure_filename cleans the filename by removing unsafe characters and paths.

It returns a safe version of the filename you can use to save files securely.

Examples
This converts spaces to underscores and keeps the extension safe.
Flask
from werkzeug.utils import secure_filename

filename = secure_filename('my photo.png')
print(filename)
This removes dangerous path parts to prevent security issues.
Flask
from werkzeug.utils import secure_filename

filename = secure_filename('../../../etc/passwd')
print(filename)
This removes special characters that are not safe in filenames.
Flask
from werkzeug.utils import secure_filename

filename = secure_filename('my*file?.txt')
print(filename)
Sample Program

This Flask app accepts a file upload, secures the filename, and saves it safely to a folder.

It prevents unsafe filenames from causing problems on the server.

Flask
from flask import Flask, request
from werkzeug.utils import secure_filename
import os

app = Flask(__name__)

UPLOAD_FOLDER = '/tmp/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    if file.filename == '':
        return 'No selected file', 400
    filename = secure_filename(file.filename)
    save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(save_path)
    return f'File saved as {filename}'

# To run this app, use: flask run
# Then send a POST request with a file to /upload
OutputSuccess
Important Notes

Always use secure_filename before saving user-uploaded files.

Make sure the upload folder exists and has proper permissions.

Secure filenames help prevent overwriting important files and directory traversal attacks.

Summary

Use secure_filename to clean user-uploaded filenames.

This protects your server from unsafe file paths and characters.

It is a simple but important step in handling file uploads securely.