fileuploads.rst
This file
Path
docs/patterns/fileuploads.rst
190 lines · 7.6 KiB
Last changed by
Merge pull request #2727 from red-alert/masterDavid Lordbefore adoption5239458
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, flash, 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.3738Why do we limit the extensions that are allowed? You probably don't want39your users to be able to upload everything there if the server is directly40sending out the data to the client. That way you can make sure that users41are not able to upload HTML files that would cause XSS problems (see42:ref:`xss`). Also make sure to disallow ``.php`` files if the server43executes them, but who has PHP installed on their server, right? :)4445Next the functions that check if an extension is valid and that uploads46the file and redirects the user to the URL for the uploaded file::4748 def allowed_file(filename):49 return '.' in filename and \50 filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS5152 @app.route('/', methods=['GET', 'POST'])53 def upload_file():54 if request.method == 'POST':55 # check if the post request has the file part56 if 'file' not in request.files:57 flash('No file part')58 return redirect(request.url)59 file = request.files['file']60 # if user does not select file, browser also61 # submit an empty part without filename62 if file.filename == '':63 flash('No selected file')64 return redirect(request.url)65 if file and allowed_file(file.filename):66 filename = secure_filename(file.filename)67 file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))68 return redirect(url_for('uploaded_file',69 filename=filename))70 return '''71 <!doctype html>72 <title>Upload new File</title>73 <h1>Upload new File</h1>74 <form method=post enctype=multipart/form-data>75 <input type=file name=file>76 <input type=submit value=Upload>77 </form>78 '''7980So what does that :func:`~werkzeug.utils.secure_filename` function actually do?81Now the problem is that there is that principle called "never trust user82input". This is also true for the filename of an uploaded file. All83submitted form data can be forged, and filenames can be dangerous. For84the moment just remember: always use that function to secure a filename85before storing it directly on the filesystem.8687.. admonition:: Information for the Pros8889 So you're interested in what that :func:`~werkzeug.utils.secure_filename`90 function does and what the problem is if you're not using it? So just91 imagine someone would send the following information as `filename` to92 your application::9394 filename = "../../../../home/username/.bashrc"9596 Assuming the number of ``../`` is correct and you would join this with97 the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on98 the server's filesystem he or she should not modify. This does require some99 knowledge about how the application looks like, but trust me, hackers100 are patient :)101102 Now let's look how that function works:103104 >>> secure_filename('../../../../home/username/.bashrc')105 'home_username_.bashrc'106107Now one last thing is missing: the serving of the uploaded files. In the108:func:`upload_file()` we redirect the user to109``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``.110So we write the :func:`uploaded_file` function to return the file of that name. As111of Flask 0.5 we can use a function that does that for us::112113 from flask import send_from_directory114115 @app.route('/uploads/<filename>')116 def uploaded_file(filename):117 return send_from_directory(app.config['UPLOAD_FOLDER'],118 filename)119120Alternatively you can register `uploaded_file` as `build_only` rule and121use the :class:`~werkzeug.wsgi.SharedDataMiddleware`. This also works with122older versions of Flask::123124 from werkzeug import SharedDataMiddleware125 app.add_url_rule('/uploads/<filename>', 'uploaded_file',126 build_only=True)127 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {128 '/uploads': app.config['UPLOAD_FOLDER']129 })130131If you now run the application everything should work as expected.132133134Improving Uploads135-----------------136137.. versionadded:: 0.6138139So how exactly does Flask handle uploads? Well it will store them in the140webserver's memory if the files are reasonable small otherwise in a141temporary location (as returned by :func:`tempfile.gettempdir`). But how142do you specify the maximum file size after which an upload is aborted? By143default Flask will happily accept file uploads to an unlimited amount of144memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``145config key::146147 from flask import Flask, Request148149 app = Flask(__name__)150 app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024151152The code above will limit the maximum allowed payload to 16 megabytes.153If a larger file is transmitted, Flask will raise a154:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.155156.. admonition:: Connection Reset Issue157158 When using the local development server, you may get a connection159 reset error instead of a 413 response. You will get the correct160 status response when running the app with a production WSGI server.161162This feature was added in Flask 0.6 but can be achieved in older versions163as well by subclassing the request object. For more information on that164consult the Werkzeug documentation on file handling.165166167Upload Progress Bars168--------------------169170A while ago many developers had the idea to read the incoming file in171small chunks and store the upload progress in the database to be able to172poll the progress with JavaScript from the client. Long story short: the173client asks the server every 5 seconds how much it has transmitted174already. Do you realize the irony? The client is asking for something it175should already know.176177An Easier Solution178------------------179180Now there are better solutions that work faster and are more reliable. There181are JavaScript libraries like jQuery_ that have form plugins to ease the182construction of progress bar.183184Because the common pattern for file uploads exists almost unchanged in all185applications dealing with uploads, there is also a Flask extension called186`Flask-Uploads`_ that implements a full fledged upload mechanism with white and187blacklisting of extensions and more.188189.. _jQuery: https://jquery.com/190.. _Flask-Uploads: https://pythonhosted.org/Flask-Uploads/