Skip to content
Myr

fileuploads.rst

This file

Path

docs/patterns/fileuploads.rst

183 lines · 7.2 KiB

Last changed by

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

History of this file

Take it

The walk stopped after 200 commits: lines older than a3e4395 point at it.

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 1–39why, one step back
1Uploading Files
2===============34Ah yes, the good old problem of file uploads. The basic idea of file5uploads is actually quite simple. It basically works like this:671. A ``<form>`` tag is marked with ``enctype=multipart/form-data``8 and an ``<input type=file>`` is placed in that form.92. The application accesses the file from the :attr:`~flask.request.files`10 dictionary on the request object.113. use the :meth:`~werkzeug.datastructures.FileStorage.save` method of the file to save12 the file permanently somewhere on the filesystem.1314A Gentle Introduction15---------------------1617Let's start with a very basic application that uploads a file to a18specific upload folder and displays a file to the user. Let's look at the19bootstrapping code for our application::2021 import os22 from flask import Flask, flash, request, redirect, url_for23 from werkzeug.utils import secure_filename2425 UPLOAD_FOLDER = '/path/to/the/uploads'26 ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}2728 app = Flask(__name__)29 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER3031So first we need a couple of imports. Most should be straightforward, the32:func:`werkzeug.secure_filename` is explained a little bit later. The33``UPLOAD_FOLDER`` is where we will store the uploaded files and the34``ALLOWED_EXTENSIONS`` is the set of allowed file extensions.3536Why do we limit the extensions that are allowed? You probably don't want37your users to be able to upload everything there if the server is directly38sending out the data to the client. That way you can make sure that users39are not able to upload HTML files that would cause XSS problems (see

remove unused ref directivesDavid Lordbefore adoption171aabc

line 40why, one step back
40:ref:`security-xss`). Also make sure to disallow ``.php`` files if the server

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 41–57why, one step back
41executes them, but who has PHP installed on their server, right? :)
4243Next the functions that check if an extension is valid and that uploads44the file and redirects the user to the URL for the uploaded file::4546 def allowed_file(filename):47 return '.' in filename and \48 filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS4950 @app.route('/', methods=['GET', 'POST'])51 def upload_file():52 if request.method == 'POST':53 # check if the post request has the file part54 if 'file' not in request.files:55 flash('No file part')56 return redirect(request.url)57 file = request.files['file']

fix grammar (#3769)miquelvirbefore adoption598c56c

lines 58–59why, one step back
58 # If the user does not select a file, the browser submits an
59 # empty file without a filename.

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 60–65why, one step back
60 if file.filename == '':
61 flash('No selected file')62 return redirect(request.url)63 if file and allowed_file(file.filename):64 filename = secure_filename(file.filename)65 file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

line 66why, one step back
66 return redirect(url_for('download_file', name=filename))

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 67–103why, one step back
67 return '''
68 <!doctype html>69 <title>Upload new File</title>70 <h1>Upload new File</h1>71 <form method=post enctype=multipart/form-data>72 <input type=file name=file>73 <input type=submit value=Upload>74 </form>75 '''7677So what does that :func:`~werkzeug.utils.secure_filename` function actually do?78Now the problem is that there is that principle called "never trust user79input". This is also true for the filename of an uploaded file. All80submitted form data can be forged, and filenames can be dangerous. For81the moment just remember: always use that function to secure a filename82before storing it directly on the filesystem.8384.. admonition:: Information for the Pros8586 So you're interested in what that :func:`~werkzeug.utils.secure_filename`87 function does and what the problem is if you're not using it? So just88 imagine someone would send the following information as `filename` to89 your application::9091 filename = "../../../../home/username/.bashrc"9293 Assuming the number of ``../`` is correct and you would join this with94 the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on95 the server's filesystem he or she should not modify. This does require some96 knowledge about how the application looks like, but trust me, hackers97 are patient :)9899 Now let's look how that function works:100101 >>> secure_filename('../../../../home/username/.bashrc')102 'home_username_.bashrc'103

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 104–107why, one step back
104We want to be able to serve the uploaded files so they can be downloaded
105by users. We'll define a ``download_file`` view to serve files in the106upload folder by name. ``url_for("download_file", name=name)`` generates107download URLs.

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

line 108why, one step back
108

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 109–110why, one step back
109.. code-block:: python
110

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 111–112why, one step back
111 from flask import send_from_directory
112

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 113–115why, one step back
113 @app.route('/uploads/<name>')
114 def download_file(name):115 return send_from_directory(app.config["UPLOAD_FOLDER"], name)

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

line 116why, one step back
116

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 117–119why, one step back
117If you're using middleware or the HTTP server to serve files, you can
118register the ``download_file`` endpoint as ``build_only`` so ``url_for``119will work without a view function.

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

line 120why, one step back
120

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

line 121why, one step back
121.. code-block:: python

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

line 122why, one step back
122

Merge pull request #3828 from pallets/move-send-fileDavid Lordbefore adoptionbbb273b

lines 123–125why, one step back
123 app.add_url_rule(
124 "/uploads/<name>", endpoint="download_file", build_only=True125 )

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 126–133why, one step back
126
127128Improving Uploads129-----------------130131.. versionadded:: 0.6132133So how exactly does Flask handle uploads? Well it will store them in the

fix grammar (#3769)miquelvirbefore adoption598c56c

line 134why, one step back
134webserver's memory if the files are reasonably small, otherwise in a

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 135–136why, one step back
135temporary location (as returned by :func:`tempfile.gettempdir`). But how
136do you specify the maximum file size after which an upload is aborted? By

fix grammar (#3769)miquelvirbefore adoption598c56c

line 137why, one step back
137default Flask will happily accept file uploads with an unlimited amount of

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 138–165why, one step back
138memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``
139config key::140141 from flask import Flask, Request142143 app = Flask(__name__)144 app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000145146The code above will limit the maximum allowed payload to 16 megabytes.147If a larger file is transmitted, Flask will raise a148:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.149150.. admonition:: Connection Reset Issue151152 When using the local development server, you may get a connection153 reset error instead of a 413 response. You will get the correct154 status response when running the app with a production WSGI server.155156This feature was added in Flask 0.6 but can be achieved in older versions157as well by subclassing the request object. For more information on that158consult the Werkzeug documentation on file handling.159160161Upload Progress Bars162--------------------163164A while ago many developers had the idea to read the incoming file in165small chunks and store the upload progress in the database to be able to

fix grammar (#3769)miquelvirbefore adoption598c56c

lines 166–168why, one step back
166poll the progress with JavaScript from the client. The client asks the
167server every 5 seconds how much it has transmitted, but this is168something it should already know.

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 169–178why, one step back
169
170An Easier Solution171------------------172173Now there are better solutions that work faster and are more reliable. There174are JavaScript libraries like jQuery_ that have form plugins to ease the175construction of progress bar.176177Because the common pattern for file uploads exists almost unchanged in all178applications dealing with uploads, there is also a Flask extension called

Merge pull request #3680 from pallets/feature/doc-fixesDavid Lordbefore adoptiona12a341

line 179why, one step back
179`Flask-Uploads`_ that implements a full fledged upload mechanism that

Merge pull request #3681 from pallets/fix-typoDavid Lordbefore adoption4e854ee

line 180why, one step back
180allows controlling which file extensions are allowed to be uploaded.

Merge pull request #3498 from raymond-devries/3445-traceback-for-noneDavid Lordbefore adoptiona3e4395

lines 181–182why, one step back
181
182.. _jQuery: https://jquery.com/

Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8

line 183why, one step back
183.. _Flask-Uploads: https://flask-uploads.readthedocs.io/en/latest/