fileuploads.rst
This file
Path
docs/patterns/fileuploads.rst
187 lines · 7.6 KiB
Last changed by
fix grammar (#3769)miquelvirbefore adoption598c56c
History of this fileTake it
The walk stopped after 200 commits: lines older than 4f3dbb3 point at it.
Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 1–39why, one step back1Uploading 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 (seeremove unused ref directivesDavid Lordbefore adoption171aabc
line 40why, one step back40:ref:`security-xss`). Also make sure to disallow ``.php`` files if the serverMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 41–57why, one step back41executes 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']fix grammar (#3769)miquelvirbefore adoption598c56c
lines 58–59why, one step back58 # If the user does not select a file, the browser submits an59 # empty file without a filename.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 60–121why, one step back60 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::121Merge branch '1.1.x'David Lordbefore adoption40eadfc
line 122why, one step back122 from werkzeug.middleware.shared_data import SharedDataMiddlewareMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 123–137why, one step back123 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 thefix grammar (#3769)miquelvirbefore adoption598c56c
line 138why, one step back138webserver's memory if the files are reasonably small, otherwise in aMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 139–140why, one step back139temporary location (as returned by :func:`tempfile.gettempdir`). But how140do you specify the maximum file size after which an upload is aborted? Byfix grammar (#3769)miquelvirbefore adoption598c56c
line 141why, one step back141default Flask will happily accept file uploads with an unlimited amount ofMerge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 142–147why, one step back142memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``143config key::144145 from flask import Flask, Request146147 app = Flask(__name__)Merge pull request #3332 from Eido95/patch-1David Lordbefore adoptiondb061cf
line 148why, one step back148 app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 149–169why, one step back149150The 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 tofix grammar (#3769)miquelvirbefore adoption598c56c
lines 170–172why, one step back170poll the progress with JavaScript from the client. The client asks the171server every 5 seconds how much it has transmitted, but this is172something it should already know.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 173–182why, one step back173174An Easier Solution175------------------176177Now there are better solutions that work faster and are more reliable. There178are JavaScript libraries like jQuery_ that have form plugins to ease the179construction of progress bar.180181Because the common pattern for file uploads exists almost unchanged in all182applications dealing with uploads, there is also a Flask extension calledMerge pull request #3680 from pallets/feature/doc-fixesDavid Lordbefore adoptiona12a341
line 183why, one step back183`Flask-Uploads`_ that implements a full fledged upload mechanism thatMerge pull request #3681 from pallets/fix-typoDavid Lordbefore adoption4e854ee
line 184why, one step back184allows controlling which file extensions are allowed to be uploaded.Merge branch '1.0-maintenance'David Lordbefore adoption4f3dbb3
lines 185–186why, one step back185186.. _jQuery: https://jquery.com/Merge pull request #3603 from jeffwidman/patch-1David Lordbefore adoptioneec29a8
line 187why, one step back187.. _Flask-Uploads: https://flask-uploads.readthedocs.io/en/latest/