Skip to content
Myr

fileuploads.rst

This file

Path

docs/patterns/fileuploads.rst

188 lines · 7.6 KiB

Last changed by

remove unused ref directivesDavid Lordbefore adoption171aabc

History of this file

Take it

1Uploading Files2===============34Ah yes, the good old problem of file uploads.  The basic idea of file5uploads is actually quite simple.  It basically works like this:671. A ``<form>`` tag is marked with ``enctype=multipart/form-data``8   and an ``<input type=file>`` is placed in that form.92. The application accesses the file from the :attr:`~flask.request.files`10   dictionary on the request object.113. use the :meth:`~werkzeug.datastructures.FileStorage.save` method of the file to save12   the file permanently somewhere on the filesystem.1314A Gentle Introduction15---------------------1617Let's start with a very basic application that uploads a file to a18specific upload folder and displays a file to the user.  Let's look at the19bootstrapping code for our application::2021    import os22    from flask import Flask, flash, request, redirect, url_for23    from werkzeug.utils import secure_filename2425    UPLOAD_FOLDER = '/path/to/the/uploads'26    ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}2728    app = Flask(__name__)29    app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER3031So first we need a couple of imports.  Most should be straightforward, the32:func:`werkzeug.secure_filename` is explained a little bit later.  The33``UPLOAD_FOLDER`` is where we will store the uploaded files and the34``ALLOWED_EXTENSIONS`` is the set of allowed file extensions.3536Why do we limit the extensions that are allowed?  You probably don't want37your users to be able to upload everything there if the server is directly38sending out the data to the client.  That way you can make sure that users39are not able to upload HTML files that would cause XSS problems (see40:ref:`security-xss`).  Also make sure to disallow ``.php`` files if the server41executes them, but who has PHP installed on their server, right?  :)4243Next the functions that check if an extension is valid and that uploads44the file and redirects the user to the URL for the uploaded file::4546    def allowed_file(filename):47        return '.' in filename and \48               filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS4950    @app.route('/', methods=['GET', 'POST'])51    def upload_file():52        if request.method == 'POST':53            # check if the post request has the file part54            if 'file' not in request.files:55                flash('No file part')56                return redirect(request.url)57            file = request.files['file']58            # if user does not select file, browser also59            # submit an empty part without filename60            if file.filename == '':61                flash('No selected file')62                return redirect(request.url)63            if file and allowed_file(file.filename):64                filename = secure_filename(file.filename)65                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))66                return redirect(url_for('uploaded_file',67                                        filename=filename))68        return '''69        <!doctype html>70        <title>Upload new File</title>71        <h1>Upload new File</h1>72        <form method=post enctype=multipart/form-data>73          <input type=file name=file>74          <input type=submit value=Upload>75        </form>76        '''7778So what does that :func:`~werkzeug.utils.secure_filename` function actually do?79Now the problem is that there is that principle called "never trust user80input".  This is also true for the filename of an uploaded file.  All81submitted form data can be forged, and filenames can be dangerous.  For82the moment just remember: always use that function to secure a filename83before storing it directly on the filesystem.8485.. admonition:: Information for the Pros8687   So you're interested in what that :func:`~werkzeug.utils.secure_filename`88   function does and what the problem is if you're not using it?  So just89   imagine someone would send the following information as `filename` to90   your application::9192      filename = "../../../../home/username/.bashrc"9394   Assuming the number of ``../`` is correct and you would join this with95   the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on96   the server's filesystem he or she should not modify.  This does require some97   knowledge about how the application looks like, but trust me, hackers98   are patient :)99100   Now let's look how that function works:101102   >>> secure_filename('../../../../home/username/.bashrc')103   'home_username_.bashrc'104105Now one last thing is missing: the serving of the uploaded files. In the106:func:`upload_file()` we redirect the user to107``url_for('uploaded_file', filename=filename)``, that is, ``/uploads/filename``.108So we write the :func:`uploaded_file` function to return the file of that name. As109of Flask 0.5 we can use a function that does that for us::110111    from flask import send_from_directory112113    @app.route('/uploads/<filename>')114    def uploaded_file(filename):115        return send_from_directory(app.config['UPLOAD_FOLDER'],116                                   filename)117118Alternatively you can register `uploaded_file` as `build_only` rule and119use the :class:`~werkzeug.wsgi.SharedDataMiddleware`.  This also works with120older versions of Flask::121122    from werkzeug.middleware.shared_data import SharedDataMiddleware123    app.add_url_rule('/uploads/<filename>', 'uploaded_file',124                     build_only=True)125    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {126        '/uploads':  app.config['UPLOAD_FOLDER']127    })128129If you now run the application everything should work as expected.130131132Improving Uploads133-----------------134135.. versionadded:: 0.6136137So how exactly does Flask handle uploads?  Well it will store them in the138webserver's memory if the files are reasonable small otherwise in a139temporary location (as returned by :func:`tempfile.gettempdir`).  But how140do you specify the maximum file size after which an upload is aborted?  By141default Flask will happily accept file uploads to an unlimited amount of142memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``143config key::144145    from flask import Flask, Request146147    app = Flask(__name__)148    app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000149150The code above will limit the maximum allowed payload to 16 megabytes.151If a larger file is transmitted, Flask will raise a152:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.153154.. admonition:: Connection Reset Issue155156    When using the local development server, you may get a connection157    reset error instead of a 413 response. You will get the correct158    status response when running the app with a production WSGI server.159160This feature was added in Flask 0.6 but can be achieved in older versions161as well by subclassing the request object.  For more information on that162consult the Werkzeug documentation on file handling.163164165Upload Progress Bars166--------------------167168A while ago many developers had the idea to read the incoming file in169small chunks and store the upload progress in the database to be able to170poll the progress with JavaScript from the client.  Long story short: the171client asks the server every 5 seconds how much it has transmitted172already.  Do you realize the irony?  The client is asking for something it173should already know.174175An Easier Solution176------------------177178Now there are better solutions that work faster and are more reliable. There179are JavaScript libraries like jQuery_ that have form plugins to ease the180construction of progress bar.181182Because the common pattern for file uploads exists almost unchanged in all183applications dealing with uploads, there is also a Flask extension called184`Flask-Uploads`_ that implements a full fledged upload mechanism with white and185blacklisting of extensions and more.186187.. _jQuery: https://jquery.com/188.. _Flask-Uploads: https://pythonhosted.org/Flask-Uploads/