🌐
Beautiful Soup
tedboy.github.io › flask › generated › werkzeug.secure_filename.html
werkzeug.secure_filename — Flask API
On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt') ...
🌐
ProgramCreek
programcreek.com › python › example › 60712 › werkzeug.secure_filename
Python Examples of werkzeug.secure_filename
You may also want to check out all available functions/classes of the module werkzeug , or try the search function . ... def upload_img(): """Upload img. 上传图片 """ if request.method == 'POST': state = { 'success' : 0, 'message' : "上传图片后缀支持 png, jpg, jpeg, gif 格式", 'url': "" } f = request.files['file'] if allowed_file(f.filename): # 采用绝对路径 filename = 'C:/nlu/data/img/' + secure_filename(f.filename) f.save(filename) state['success'] = 1 state['message'] = "上传图片成功" state['url'] = filename return json.dumps(state)
Discussions

'Secure' Filenames
An example: if the user supplied a file name of ../../../../../boot/vmlinuz and your app was running as root -bad practice but still common - you might write over your Linux kernel with the uploaded file if your didn't sanitize the input. More on reddit.com
🌐 r/Python
4
6
January 14, 2017
werkzeug - Flask - Do I need to use secure_filename() on uploads to S3/Google Cloud? - Stack Overflow
In the Flask documentation for file uploads, they recommend use of secure_filename() to sanitize a file's name before storing it. Here's their example: uploaded_file = request.files['file'] if More on stackoverflow.com
🌐 stackoverflow.com
secure_filename in werkzeug.util is problematic when the file name isnon-ASCII characters
if the file name is non-ASCII characters then using secure_filename will result become wired so How can I solve this problem If I'm going to do my own secure_filename where should I put my code... More on github.com
🌐 github.com
3
March 29, 2016
python - cannot import name 'secure_filename' from 'werkzeug' - Stack Overflow
I'm trying to import secure_filename from werkzeug.utils and it shoot an error. It works fine under my base virtual env. code: # Flask packages from flask import Flask, render_template, request, se... More on stackoverflow.com
🌐 stackoverflow.com
🌐
ProgramCreek
programcreek.com › python › example › 96284 › werkzeug.utils.secure_filename
Python Examples of werkzeug.utils.secure_filename
def upload_csv() -> str: """Upload CSV example.""" submitted_file = request.files["file"] if submitted_file and allowed_filename(submitted_file.filename): filename = secure_filename(submitted_file.filename) directory = os.path.join(app.config["UPLOAD_FOLDER"]) if not os.path.exists(directory): os.mkdir(directory) basedir = os.path.abspath(os.path.dirname(__file__)) submitted_file.save( os.path.join(basedir, app.config["UPLOAD_FOLDER"], filename) ) out = { "status": HTTPStatus.OK, "filename": filename, "message": f"{filename} saved successful.", } return jsonify(out)
🌐
Medium
medium.com › @sujathamudadla1213 › what-is-the-use-of-secure-filename-in-flask-9eef4c71503b
What is the use of secure_filename in flask? | by Sujatha Mudadla | Medium
November 25, 2023 - What is the use of secure_filename in flask? from werkzeug.utils import secure_filename @app.route(‘/upload’, methods=[‘GET’, ‘POST’]) def upload_file(): if request.method == …
🌐
HotExamples
python.hotexamples.com › examples › werkzeug.utils › - › secure_filename › python-secure_filename-function-examples.html
Python secure_filename Examples, werkzeug.utils.secure_filename Python Examples - HotExamples
Received ' + file_type + ' should be ' + platform.extension) except Exception, e: return jsonify(result='ERROR', file_name=filename_noExtension, file_type=file_type, msg=str(e)) ... def upload_site_images(): if request.files and len(request.files) > 0 and request.files['file']: file_body = request.files['file'] if allowed_files(secure_filename(file_body.filename)): filename = secure_filename(str(uuid4()) + "." + file_body.filename.split('.')[1]) file_body.save(os.path.join(upload_folder, filename)) return json.dumps({"status": "success", "id": filename, "filename": filename}) return '', 404
🌐
Reddit
reddit.com › r/python › 'secure' filenames
r/Python on Reddit: 'Secure' Filenames
January 14, 2017 -

Flask's WSGI library werkzeug has a utility function called secure_filename - you're intended to pass the filename of a user uploaded file to it but I'm having trouble understanding what exactly the concern is, and what securing a filename could possibly entail.

The Pooco site notes

what does that secure_filename() function actually do? Now the problem is that there is that principle called “never trust user input”. This is also true for the filename of an uploaded file. All submitted form data can be forged, and filenames can be dangerous. For the moment just remember: always use that function to secure a filename before storing it directly on the filesystem.

What's returned is the exact same filename except I guess sanitized in some way. What my concern is is that I don't really understand what this function accomplishes. I plan on changing the filename of any user submitted file anyways (random uuid string with a suffix of '-small', '-large', etc.). Does it do me any good to first run the filename through secure_filename() and then change the actual filename? Can I just initially change the filename?

🌐
GitHub
github.com › pallets › werkzeug › blob › main › src › werkzeug › utils.py
werkzeug/src/werkzeug/utils.py at main · pallets/werkzeug
def secure_filename(filename: str) -> str: r"""Pass it a filename and it will return a secure version of it. This · filename can then safely be stored on a regular file system and passed · to :func:`os.path.join`. The filename ...
Author   pallets
🌐
Snyk
snyk.io › advisor › werkzeug › functions › werkzeug.utils.secure_filename
How to use the werkzeug.utils.secure_filename function in Werkzeug | Snyk
def handle_uploaded_file(self): # http://flask.pocoo.org/docs/1.0/api/#flask.Request.form # file = request.files['file'] # Non-ASCII would be omitted and resulting the filename as to 'egg' or 'tar.gz' filename = secure_filename(file.filename) # tar.xz only works on Linux and macOS if filename in ['egg', 'zip', 'tar.gz']: filename = '%s_%s.%s' % (self.project, self.version, filename) else: filename = '%s_%s_from_file_%s' % (self.project, self.version, filename) if filename.endswith('egg'): self.eggname = filename self.eggpath = os.path.join(self.DEPLOY_PATH, self.eggname) file.save(self.eggpath) self.scrapy_cfg_not_found = False else: # Compressed file filepath = os.path.join(self.DEPLOY_PATH, filename) file.save(filepath) tmpdir = self.uncompress_to_tmpdir(filepath)
Top answer
1 of 1
7

You are correct.

You only need to use the secure_filename function if you are using the value of request.files['file'].filename to build a filepath destined for your filesystem - for example as an argument to os.path.join.

As you're using a UUID for the filename, the user input value is disregarded anyway.

Even without S3, it would also be safe NOT to use secure_filename if you used a UUID as the filename segment of the filepath on your local filesystem. For example:

uploaded_file = request.files['file']
if uploaded_file:
    file_uuid = uuid.uuid4()
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file_uuid))
    # Rest of code

In either scenario you'd then store the UUID somewhere in the database. Whether you store the originally provided request.files['file'].filename value alongside that is your choice.

This might make sense if you want the user to see the original name of the file when they uploaded it. In that case it's definitey wise to run the value through secure_filename anyway, so there's never a situation where the frontend displays a listing to a user which includes a file called ../../../../ohdear.txt


the secure_filename docstring also points out some other functionality:

Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to :func:os.path.join. The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files.

>>> secure_filename("My cool movie.mov")
'My_cool_movie.mov'
>>> secure_filename("../../../etc/passwd")
'etc_passwd'
>>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
'i_contain_cool_umlauts.txt'
Find elsewhere
🌐
Werkzeug
werkzeug.palletsprojects.com › en › stable › utils
Utilities — Werkzeug Documentation (3.1.x)
Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to os.path.join().
🌐
Beautiful Soup
tedboy.github.io › flask › _modules › werkzeug › utils.html
werkzeug.utils — Flask API
On windows systems the function also makes sure that the file is not named after one of the special device files. >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt') ...
🌐
TestDriven.io
testdriven.io › tips › 71b62504-39d7-43ee-8ca2-715a42fc97c7
Tips and Tricks - Flask File Uploads | TestDriven.io
import os from flask import request, current_app from werkzeug.utils import secure_filename @journal_blueprint.route('/upload_file', methods=['POST']) def upload_file(): if 'file' in request.files: file = request.files['file'] filename = secure_filename(file.filename) file.save(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)) return '<p>File uploaded!</p>'
🌐
OneUptime
oneuptime.com › home › blog › how to handle file uploads in flask
How to Handle File Uploads in Flask
February 2, 2026 - A production-ready file upload needs to validate the file type, sanitize the filename, and limit the file size. This example adds all three protections. # secure_upload.py # Secure Flask file upload with validation from flask import Flask, request, jsonify from werkzeug.utils import secure_filename import os import uuid app = Flask(__name__) # Configuration UPLOAD_FOLDER = '/var/uploads' MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # 16 MB max file size ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx'} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.config['MAX_CONTENT_LENGTH']
🌐
Miguel Grinberg
blog.miguelgrinberg.com › post › handling-file-uploads-with-flask
Handling File Uploads With Flask - miguelgrinberg.com
July 8, 2020 - Let's incorporate secure_filename() into the example upload server, and also add a configuration variable that defines a dedicated location for file uploads. Here is the complete app.py source file with secure filenames: import os from flask import Flask, render_template, request, redirect, url_for, abort from werkzeug.utils import secure_filename app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 app.config['UPLOAD_EXTENSIONS'] = ['.jpg', '.png', '.gif'] app.config['UPLOAD_PATH'] = 'uploads' @app.route('/') def index(): return render_template('index.html') @app.route('/', me
🌐
GitHub
github.com › pallets › werkzeug › issues › 883
secure_filename in werkzeug.util is problematic when the file name isnon-ASCII characters · Issue #883 · pallets/werkzeug
March 29, 2016 - if the file name is non-ASCII characters then using secure_filename will result become wired so How can I solve this problem If I'm going to do my own secure_filename where should I put my code...
Author   pallets
Top answer
1 of 3
8

Flask-Uploads is actually using the patterns found in Flask's documentation for file upload handling. It uses werkzeug.secure_filename, it provides a way to set MAX_CONTENT_LENGTH if, for some reason, you are using Flask 0.5 or older, and it provides a way to validate files based on their extension.

In fact, Flask's documentation actually explicitly suggests using Flask-Uploads:

Because the common pattern for file uploads exists almost unchanged in all applications dealing with uploads, there is a Flask extension called Flask-Uploads that implements a full fledged upload mechanism with white and blacklisting of extensions and more.

2 of 3
0

I ended up with using my own secure_filename in my case that supports Arabic:

import os
import re
import unicodedata

# edit this to add more characters
_filename_ascii_strip_re = re.compile(r"[^A-Za-z0-9\u0600-\u06FF_.-]")
_windows_device_files = {
    "CON",
    "PRN",
    "AUX",
    "NUL",
    *(f"COM{i}" for i in range(10)),
    *(f"LPT{i}" for i in range(10)),
}

def secure_filename(filename: str) -> str:
    # Normalize the filename to handle UTF-8 characters
    filename = unicodedata.normalize("NFKC", filename)

    # Replace path separators with spaces
    for sep in os.sep, os.path.altsep:
        if sep:
            filename = filename.replace(sep, " ")

    # Remove unsafe characters
    filename = str(_filename_ascii_strip_re.sub("", "_".join(filename.split()))).strip("._")

    # Ensure the filename is not a reserved device name on Windows
    if os.name == "nt" and filename and filename.split(".")[0].upper() in _windows_device_files:
        filename = f"_{filename}"

    return filename



🌐
Flask
flask.palletsprojects.com › en › stable › patterns › fileuploads
Uploading Files — Flask Documentation (3.1.x)
import os from flask import Flask, flash, request, redirect, url_for from werkzeug.utils import secure_filename UPLOAD_FOLDER = '/path/to/the/uploads' ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'} app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER