Skip to content
Myr

fileuploads.rst

This file

Path

docs/patterns/fileuploads.rst

180 lines · 7.1 KiB

Last changed by

Fixed an rst errorArmin Ronacherbefore adoptiondbb3620

History of this file

Take it

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

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

lines 1–100why, 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.133. use the :meth:`~werkzeug.FileStorage.save` method of the file to save14 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 users44are not able to upload HTML files that would cause XSS problems. Also45make sure to disallow `.php` files if the server executes them, but who46has PHP installed on his server, right? :)4748Next 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 '''7374So what does that :func:`~werkzeug.secure_filename` function actually do?75Now the problem is that there is that principle called "never trust user76input". 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 Pros8283 So you're interested in what that :func:`~werkzeug.secure_filename`84 function does and what the problem is if you're not using it? So just85 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'100

send_from_directory > SharedDataMiddlewareArmin Ronacherbefore adoptionf1a6fbe

lines 101–102why, one step back
101Now one last thing is missing: the serving of the uploaded files. As of
102Flask 0.5 we can use a function that does that for us::

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

line 103why, one step back
103

send_from_directory > SharedDataMiddlewareArmin Ronacherbefore adoptionf1a6fbe

lines 104–114why, one step back
104 from flask import send_from_directory
105106 @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 and112use the :class:`~werkzeug.SharedDataMiddleware`. This also works with113older versions of Flask::114

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

line 115why, one step back
115 from werkzeug import SharedDataMiddleware

send_from_directory > SharedDataMiddlewareArmin Ronacherbefore adoptionf1a6fbe

lines 116–117why, one step back
116 app.add_url_rule('/uploads/<filename>', 'uploaded_file',
117 build_only=True)

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

lines 118–127why, one step back
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

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

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::

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

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

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

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.

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

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

Typo fix. That is what was meant, right?Simon Sapinbefore adoption54d22f1

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/