fileuploads.rst
This file
Path
docs/patterns/fileuploads.rst
190 lines · 7.6 KiB
Last changed by
Merge pull request #1062 from SteelyWing/patch-2Kenneth Reitzbefore adoption16a7dd0
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.utils 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 # check if the post request has the file part60 if 'file' not in request.files:61 flash('No file part')62 return redirect(request.url)63 file = request.files['file']64 # if user does not select file, browser also65 # submit a empty part without filename66 if file.filename == '':67 flash('No selected file')68 return redirect(request.url)69 if file and allowed_file(file.filename):70 filename = secure_filename(file.filename)71 file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))72 return redirect(url_for('uploaded_file',73 filename=filename))74 return '''75 <!doctype html>76 <title>Upload new File</title>77 <h1>Upload new File</h1>78 <form action="" method=post enctype=multipart/form-data>79 <p><input type=file name=file>80 <input type=submit value=Upload>81 </form>82 '''8384So what does that :func:`~werkzeug.utils.secure_filename` function actually do?85Now the problem is that there is that principle called "never trust user86input". This is also true for the filename of an uploaded file. All87submitted form data can be forged, and filenames can be dangerous. For88the moment just remember: always use that function to secure a filename89before storing it directly on the filesystem.9091.. admonition:: Information for the Pros9293 So you're interested in what that :func:`~werkzeug.utils.secure_filename`94 function does and what the problem is if you're not using it? So just95 imagine someone would send the following information as `filename` to96 your application::9798 filename = "../../../../home/username/.bashrc"99100 Assuming the number of ``../`` is correct and you would join this with101 the `UPLOAD_FOLDER` the user might have the ability to modify a file on102 the server's filesystem he or she should not modify. This does require some103 knowledge about how the application looks like, but trust me, hackers104 are patient :)105106 Now let's look how that function works:107108 >>> secure_filename('../../../../home/username/.bashrc')109 'home_username_.bashrc'110111Now one last thing is missing: the serving of the uploaded files. As of112Flask 0.5 we can use a function that does that for us::113114 from flask import send_from_directory115116 @app.route('/uploads/<filename>')117 def uploaded_file(filename):118 return send_from_directory(app.config['UPLOAD_FOLDER'],119 filename)120121Alternatively you can register `uploaded_file` as `build_only` rule and122use the :class:`~werkzeug.wsgi.SharedDataMiddleware`. This also works with123older versions of Flask::124125 from werkzeug import SharedDataMiddleware126 app.add_url_rule('/uploads/<filename>', 'uploaded_file',127 build_only=True)128 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {129 '/uploads': app.config['UPLOAD_FOLDER']130 })131132If you now run the application everything should work as expected.133134135Improving Uploads136-----------------137138.. versionadded:: 0.6139140So how exactly does Flask handle uploads? Well it will store them in the141webserver's memory if the files are reasonable small otherwise in a142temporary location (as returned by :func:`tempfile.gettempdir`). But how143do you specify the maximum file size after which an upload is aborted? By144default Flask will happily accept file uploads to an unlimited amount of145memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``146config key::147148 from flask import Flask, Request149150 app = Flask(__name__)151 app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024152153The code above will limited the maximum allowed payload to 16 megabytes.154If a larger file is transmitted, Flask will raise an155:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.156157This feature was added in Flask 0.6 but can be achieved in older versions158as well by subclassing the request object. For more information on that159consult the Werkzeug documentation on file handling.160161162Upload Progress Bars163--------------------164165A while ago many developers had the idea to read the incoming file in166small chunks and store the upload progress in the database to be able to167poll the progress with JavaScript from the client. Long story short: the168client asks the server every 5 seconds how much it has transmitted169already. Do you realize the irony? The client is asking for something it170should already know.171172Now there are better solutions to that work faster and more reliable. The173web changed a lot lately and you can use HTML5, Java, Silverlight or Flash174to get a nicer uploading experience on the client side. Look at the175following libraries for some nice examples how to do that:176177- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash178- `SWFUpload <http://www.swfupload.org/>`_ - Flash179- `JumpLoader <http://jumploader.com/>`_ - Java180181182An Easier Solution183------------------184185Because the common pattern for file uploads exists almost unchanged in all186applications dealing with uploads, there is a Flask extension called187`Flask-Uploads`_ that implements a full fledged upload mechanism with188white and blacklisting of extensions and more.189190.. _Flask-Uploads: http://pythonhosted.org/Flask-Uploads/