Skip to content
Myr

fileuploads.rst

This file

Path

docs/patterns/fileuploads.rst

180 lines · 7.2 KiB

Last changed by

fixing cross-referenced links on fileupload patterns pagematt swansonbefore adoption4046d3b

History of this file

Take it

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

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 1–12why, one step back
1.. _uploading-files:
23Uploading Files4===============56Ah yes, the good old problem of file uploads. The basic idea of file7uploads is actually quite simple. It basically works like this:891. A ``<form>`` tag is marked with ``enctype=multipart/form-data``10 and an ``<input type=file>`` is placed in that form.112. The application accesses the file from the :attr:`~flask.request.files`12 dictionary on the request object.

fixing cross-referenced links on fileupload patterns pagematt swansonbefore adoption4046d3b

line 13why, one step back
133. use the :meth:`~werkzeug.datastructures.FileStorage.save` method of the file to save

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 14–43why, one step back
14 the file permanently somewhere on the filesystem.
1516A Gentle Introduction17---------------------1819Let's start with a very basic application that uploads a file to a20specific upload folder and displays a file to the user. Let's look at the21bootstrapping code for our application::2223 import os24 from flask import Flask, request, redirect, url_for25 from werkzeug import secure_filename2627 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])2930 app = Flask(__name__)3132So first we need a couple of imports. Most should be straightforward, the33:func:`werkzeug.secure_filename` is explained a little bit later. The34`UPLOAD_FOLDER` is where we will store the uploaded files and the35`ALLOWED_EXTENSIONS` is the set of allowed file extensions. Then we add a36URL rule by hand to the application. Now usually we're not doing that, so37why here? The reasons is that we want the webserver (or our development38server) to serve these files for us and so we only need a rule to generate39the URL to these files.4041Why do we limit the extensions that are allowed? You probably don't want42your users to be able to upload everything there if the server is directly43sending out the data to the client. That way you can make sure that users

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption5ecf01d

lines 44–46why, one step back
44are not able to upload HTML files that would cause XSS problems (see
45:ref:`xss`). Also make sure to disallow `.php` files if the server46executes them, but who has PHP installed on his server, right? :)

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 47–73why, one step back
47
48Next the functions that check if an extension is valid and that uploads49the file and redirects the user to the URL for the uploaded file::5051 def allowed_file(filename):52 return '.' in filename and \53 filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS5455 @app.route('/', methods=['GET', 'POST'])56 def upload_file():57 if request.method == 'POST':58 file = request.files['file']59 if file and allowed_file(file.filename):60 filename = secure_filename(file.filename)61 file.save(os.path.join(UPLOAD_FOLDER, filename))62 return redirect(url_for('uploaded_file',63 filename=filename))64 return '''65 <!doctype html>66 <title>Upload new File</title>67 <h1>Upload new File</h1>68 <form action="" method=post enctype=multipart/form-data>69 <p><input type=file name=file>70 <input type=submit value=Upload>71 </form>72 '''73

fixing cross-referenced links on fileupload patterns pagematt swansonbefore adoption4046d3b

line 74why, one step back
74So what does that :func:`~werkzeug.utils.secure_filename` function actually do?

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 75–82why, one step back
75Now the problem is that there is that principle called "never trust user
76input". This is also true for the filename of an uploaded file. All77submitted form data can be forged, and filenames can be dangerous. For78the moment just remember: always use that function to secure a filename79before storing it directly on the filesystem.8081.. admonition:: Information for the Pros82

fixing cross-referenced links on fileupload patterns pagematt swansonbefore adoption4046d3b

line 83why, one step back
83 So you're interested in what that :func:`~werkzeug.utils.secure_filename`

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 84–111why, one step back
84 function does and what the problem is if you're not using it? So just
85 imagine someone would send the following information as `filename` to86 your application::8788 filename = "../../../../home/username/.bashrc"8990 Assuming the number of ``../`` is correct and you would join this with91 the `UPLOAD_FOLDER` the user might have the ability to modify a file on92 the server's filesystem he should not modify. This does require some93 knowledge about how the application looks like, but trust me, hackers94 are patient :)9596 Now let's look how that function works:9798 >>> secure_filename('../../../../home/username/.bashrc')99 'home_username_.bashrc'100101Now one last thing is missing: the serving of the uploaded files. As of102Flask 0.5 we can use a function that does that for us::103104 from flask import send_from_directory105106 @app.route('/uploads/<filename>')107 def uploaded_file(filename):108 return send_from_directory(app.config['UPLOAD_FOLDER'],109 filename)110111Alternatively you can register `uploaded_file` as `build_only` rule and

fixing cross-referenced links on fileupload patterns pagematt swansonbefore adoption4046d3b

line 112why, one step back
112use the :class:`~werkzeug.wsgi.SharedDataMiddleware`. This also works with

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 113–127why, one step back
113older versions of Flask::
114115 from werkzeug import SharedDataMiddleware116 app.add_url_rule('/uploads/<filename>', 'uploaded_file',117 build_only=True)118 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {119 '/uploads': UPLOAD_FOLDER120 })121122If you now run the application everything should work as expected.123124125Improving Uploads126-----------------127

Documented MAX_CONTENT_LENGTH in the file upload docs and linked to Flask-UploadsArmin Ronacherbefore adoption54ebd88

lines 128–129why, one step back
128.. versionadded:: 0.6
129

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 130–134why, one step back
130So how exactly does Flask handle uploads? Well it will store them in the
131webserver's memory if the files are reasonable small otherwise in a132temporary location (as returned by :func:`tempfile.gettempdir`). But how133do you specify the maximum file size after which an upload is aborted? By134default Flask will happily accept file uploads to an unlimited amount of

Fixed an rst errorArmin Ronacherbefore adoptiondbb3620

line 135why, one step back
135memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``

Documented MAX_CONTENT_LENGTH in the file upload docs and linked to Flask-UploadsArmin Ronacherbefore adoption54ebd88

line 136why, one step back
136config key::

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 137–140why, one step back
137
138 from flask import Flask, Request139140 app = Flask(__name__)

Documented MAX_CONTENT_LENGTH in the file upload docs and linked to Flask-UploadsArmin Ronacherbefore adoption54ebd88

line 141why, one step back
141 app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 142–146why, one step back
142
143The code above will limited the maximum allowed payload to 16 megabytes.144If a larger file is transmitted, Flask will raise an145:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.146

Documented MAX_CONTENT_LENGTH in the file upload docs and linked to Flask-UploadsArmin Ronacherbefore adoption54ebd88

lines 147–149why, one step back
147This feature was added in Flask 0.6 but can be achieved in older versions
148as well by subclassing the request object. For more information on that149consult the Werkzeug documentation on file handling.

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

line 150why, one step back
150

Documented MAX_CONTENT_LENGTH in the file upload docs and linked to Flask-UploadsArmin Ronacherbefore adoption54ebd88

line 151why, one step back
151

endpoint is optional for modules. This fixes #86Armin Ronacherbefore adoptionf5b8c08

lines 152–169why, one step back
152Upload Progress Bars
153--------------------154155A while ago many developers had the idea to read the incoming file in156small chunks and store the upload progress in the database to be able to157poll the progress with JavaScript from the client. Long story short: the158client asks the server every 5 seconds how much he has transmitted159already. Do you realize the irony? The client is asking for something he160should already know.161162Now there are better solutions to that work faster and more reliable. The163web changed a lot lately and you can use HTML5, Java, Silverlight or Flash164to get a nicer uploading experience on the client side. Look at the165following libraries for some nice examples how to do that:166167- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash168- `SWFUpload <http://www.swfupload.org/>`_ - Flash169- `JumpLoader <http://jumploader.com/>`_ - Java

Documented MAX_CONTENT_LENGTH in the file upload docs and linked to Flask-UploadsArmin Ronacherbefore adoption54ebd88

lines 170–180why, one step back
170
171172An Easier Solution173------------------174175Because the common pattern for file uploads exists almost unchanged in all176applications dealing with uploads, there is a Flask extension called177`Flask-Uploads`_ that implements a full fledged upload mechanism with178white and blacklisting of extensions and more.179180.. _Flask-Uploads: http://packages.python.org/Flask-Uploads/