fileuploads.rst
This file
Path
docs/patterns/fileuploads.rst
181 lines · 7.2 KiB
Last changed by
Not known.
History of this fileTake it
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.datastructures.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__)31 app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER3233So first we need a couple of imports. Most should be straightforward, the34:func:`werkzeug.secure_filename` is explained a little bit later. The35`UPLOAD_FOLDER` is where we will store the uploaded files and the36`ALLOWED_EXTENSIONS` is the set of allowed file extensions. Then we add a37URL rule by hand to the application. Now usually we're not doing that, so38why here? The reasons is that we want the webserver (or our development39server) to serve these files for us and so we only need a rule to generate40the URL to these files.4142Why do we limit the extensions that are allowed? You probably don't want43your users to be able to upload everything there if the server is directly44sending out the data to the client. That way you can make sure that users45are not able to upload HTML files that would cause XSS problems (see46:ref:`xss`). Also make sure to disallow `.php` files if the server47executes them, but who has PHP installed on his server, right? :)4849Next the functions that check if an extension is valid and that uploads50the file and redirects the user to the URL for the uploaded file::5152 def allowed_file(filename):53 return '.' in filename and \54 filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS5556 @app.route('/', methods=['GET', 'POST'])57 def upload_file():58 if request.method == 'POST':59 file = request.files['file']60 if file and allowed_file(file.filename):61 filename = secure_filename(file.filename)62 file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))63 return redirect(url_for('uploaded_file',64 filename=filename))65 return '''66 <!doctype html>67 <title>Upload new File</title>68 <h1>Upload new File</h1>69 <form action="" method=post enctype=multipart/form-data>70 <p><input type=file name=file>71 <input type=submit value=Upload>72 </form>73 '''7475So what does that :func:`~werkzeug.utils.secure_filename` function actually do?76Now the problem is that there is that principle called "never trust user77input". This is also true for the filename of an uploaded file. All78submitted form data can be forged, and filenames can be dangerous. For79the moment just remember: always use that function to secure a filename80before storing it directly on the filesystem.8182.. admonition:: Information for the Pros8384 So you're interested in what that :func:`~werkzeug.utils.secure_filename`85 function does and what the problem is if you're not using it? So just86 imagine someone would send the following information as `filename` to87 your application::8889 filename = "../../../../home/username/.bashrc"9091 Assuming the number of ``../`` is correct and you would join this with92 the `UPLOAD_FOLDER` the user might have the ability to modify a file on93 the server's filesystem he or she should not modify. This does require some94 knowledge about how the application looks like, but trust me, hackers95 are patient :)9697 Now let's look how that function works:9899 >>> secure_filename('../../../../home/username/.bashrc')100 'home_username_.bashrc'101102Now one last thing is missing: the serving of the uploaded files. As of103Flask 0.5 we can use a function that does that for us::104105 from flask import send_from_directory106107 @app.route('/uploads/<filename>')108 def uploaded_file(filename):109 return send_from_directory(app.config['UPLOAD_FOLDER'],110 filename)111112Alternatively you can register `uploaded_file` as `build_only` rule and113use the :class:`~werkzeug.wsgi.SharedDataMiddleware`. This also works with114older versions of Flask::115116 from werkzeug import SharedDataMiddleware117 app.add_url_rule('/uploads/<filename>', 'uploaded_file',118 build_only=True)119 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {120 '/uploads': app.config['UPLOAD_FOLDER']121 })122123If you now run the application everything should work as expected.124125126Improving Uploads127-----------------128129.. versionadded:: 0.6130131So how exactly does Flask handle uploads? Well it will store them in the132webserver's memory if the files are reasonable small otherwise in a133temporary location (as returned by :func:`tempfile.gettempdir`). But how134do you specify the maximum file size after which an upload is aborted? By135default Flask will happily accept file uploads to an unlimited amount of136memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``137config key::138139 from flask import Flask, Request140141 app = Flask(__name__)142 app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024143144The code above will limited the maximum allowed payload to 16 megabytes.145If a larger file is transmitted, Flask will raise an146:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.147148This feature was added in Flask 0.6 but can be achieved in older versions149as well by subclassing the request object. For more information on that150consult the Werkzeug documentation on file handling.151152153Upload Progress Bars154--------------------155156A while ago many developers had the idea to read the incoming file in157small chunks and store the upload progress in the database to be able to158poll the progress with JavaScript from the client. Long story short: the159client asks the server every 5 seconds how much it has transmitted160already. Do you realize the irony? The client is asking for something it161should already know.162163Now there are better solutions to that work faster and more reliable. The164web changed a lot lately and you can use HTML5, Java, Silverlight or Flash165to get a nicer uploading experience on the client side. Look at the166following libraries for some nice examples how to do that:167168- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash169- `SWFUpload <http://www.swfupload.org/>`_ - Flash170- `JumpLoader <http://jumploader.com/>`_ - Java171172173An Easier Solution174------------------175176Because the common pattern for file uploads exists almost unchanged in all177applications dealing with uploads, there is a Flask extension called178`Flask-Uploads`_ that implements a full fledged upload mechanism with179white and blacklisting of extensions and more.180181.. _Flask-Uploads: http://packages.python.org/Flask-Uploads/