fileuploads.rst
This file
Path
docs/patterns/fileuploads.rst
160 lines · 6.6 KiB
Last changed by
Fixed some documentation issues. This fixes #41.Armin Ronacherbefore adoption854e0e2
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.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.add_url_rule('/uploads/<filename>', 'uploaded_file',32 build_only=True)3334So first we need a couple of imports. Most should be straightforward, the35:func:`werkzeug.secure_filename` is explained a little bit later. The36`UPLOAD_FOLDER` is where we will store the uploaded files and the37`ALLOWED_EXTENSIONS` is the set of allowed file extensions. Then we add a38URL rule by hand to the application. Now usually we're not doing that, so39why here? The reasons is that we want the webserver (or our development40server) to serve these files for us and so we only need a rule to generate41the URL to these files.4243Why do we limit the extensions that are allowed? You probably don't want44your users to be able to upload everything there if the server is directly45sending out the data to the client. That way you can make sure that users46are not able to upload HTML files that would cause XSS problems. Also47make sure to disallow `.php` files if the server executes them, but who48has PHP installed on his server, right? :)4950Next the functions that check if an extension is valid and that uploads51the file and redirects the user to the URL for the uploaded file::5253 def allowed_file(filename):54 return '.' in filename and \55 filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS5657 @app.route('/', methods=['GET', 'POST'])58 def upload_file():59 if request.method == 'POST':60 file = request.files['file']61 if file and allowed_file(file.filename):62 filename = secure_filename(file.filename)63 file.save(os.path.join(UPLOAD_FOLDER, filename))64 return redirect(url_for('uploaded_file',65 filename=filename))66 return '''67 <!doctype html>68 <title>Upload new File</title>69 <h1>Upload new File</h1>70 <form action="" method=post enctype=multipart/form-data>71 <p><input type=file name=file>72 <input type=submit value=Upload>73 </form>74 '''7576So what does that :func:`~werkzeug.secure_filename` function actually do?77Now the problem is that there is that principle called "never trust user78input". This is also true for the filename of an uploaded file. All79submitted form data can be forged, and filenames can be dangerous. For80the moment just remember: always use that function to secure a filename81before storing it directly on the filesystem.8283.. admonition:: Information for the Pros8485 So you're interested in what that :func:`~werkzeug.secure_filename`86 function does and what the problem is if you're not using it? So just87 imagine someone would send the following information as `filename` to88 your application::8990 filename = "../../../../home/username/.bashrc"9192 Assuming the number of ``../`` is correct and you would join this with93 the `UPLOAD_FOLDER` the user might have the ability to modify a file on94 the server's filesystem he should not modify. This does require some95 knowledge about how the application looks like, but trust me, hackers96 are patient :)9798 Now let's look how that function works:99100 >>> secure_filename('../../../../home/username/.bashrc')101 'home_username_.bashrc'102103Now if we run that application, you will notice that uploading works, but104you won't actually see that uploaded file. Well, you would have to105configure the server to serve that file for you. This is not handy for106development situations or when you are just too lazy to properly set up107the server. Would be nice to have the files still be available in that108situation, and that is really easy to do, just hook in a middleware::109110 from werkzeug import SharedDataMiddleware111 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {112 '/uploads': UPLOAD_FOLDER113 })114115If you now run the application everything should work as expected.116117118Improving Uploads119-----------------120121So how exactly does Flask handle uploads? Well it will store them in the122webserver's memory if the files are reasonable small otherwise in a123temporary location (as returned by :func:`tempfile.gettempdir`). But how124do you specify the maximum file size after which an upload is aborted? By125default Flask will happily accept file uploads to an unlimited amount of126memory, but you can limit that by subclassing the request and overriding127the Werkzeug provided :attr:`~werkzeug.BaseRequest.max_form_memory_size`128attribute::129130 from flask import Flask, Request131132 class LimitedRequest(Request):133 max_form_memory_size = 16 * 1024 * 1024134135 app = Flask(__name__)136 app.request_class = LimitedRequest137138The code above will limited the maximum allowed payload to 16 megabytes.139If a larger file is transmitted, Flask will raise an140:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.141142143Upload Progress Bars144--------------------145146A while ago many developers had the idea to read the incoming file in147small chunks and store the upload progress in the database to be able to148poll the progress with JavaScript from the client. Long story short: the149client asks the server every 5 seconds how much he has transmitted150already. Do you realize the irony? The client is asking for something he151should already know.152153Now there are better solutions to that work faster and more reliable. The154web changed a lot lately and you can use HTML5, Java, Silverlight or Flash155to get a nicer uploading experience on the client side. Look at the156following libraries for some nice examples how to do that:157158- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash159- `SWFUpload <http://www.swfupload.org/>`_ - Flash160- `JumpLoader <http://jumploader.com/>`_ - Java