fileuploads.rst
This file
Path
docs/patterns/fileuploads.rst
182 lines · 7.1 KiB
Last changed by
Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption53eef27
History of this fileTake it
The walk stopped after 200 commits: lines older than 4240ace point at it.
Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace
lines 1–177why, 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 (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 the user does not select a file, the browser submits an59 # empty file without a filename.60 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('download_file', name=filename))67 return '''68 <!doctype html>69 <title>Upload new File</title>70 <h1>Upload new File</h1>71 <form method=post enctype=multipart/form-data>72 <input type=file name=file>73 <input type=submit value=Upload>74 </form>75 '''7677So what does that :func:`~werkzeug.utils.secure_filename` function actually do?78Now the problem is that there is that principle called "never trust user79input". This is also true for the filename of an uploaded file. All80submitted form data can be forged, and filenames can be dangerous. For81the moment just remember: always use that function to secure a filename82before storing it directly on the filesystem.8384.. admonition:: Information for the Pros8586 So you're interested in what that :func:`~werkzeug.utils.secure_filename`87 function does and what the problem is if you're not using it? So just88 imagine someone would send the following information as `filename` to89 your application::9091 filename = "../../../../home/username/.bashrc"9293 Assuming the number of ``../`` is correct and you would join this with94 the ``UPLOAD_FOLDER`` the user might have the ability to modify a file on95 the server's filesystem he or she should not modify. This does require some96 knowledge about how the application looks like, but trust me, hackers97 are patient :)9899 Now let's look how that function works:100101 >>> secure_filename('../../../../home/username/.bashrc')102 'home_username_.bashrc'103104We want to be able to serve the uploaded files so they can be downloaded105by users. We'll define a ``download_file`` view to serve files in the106upload folder by name. ``url_for("download_file", name=name)`` generates107download URLs.108109.. code-block:: python110111 from flask import send_from_directory112113 @app.route('/uploads/<name>')114 def download_file(name):115 return send_from_directory(app.config["UPLOAD_FOLDER"], name)116117If you're using middleware or the HTTP server to serve files, you can118register the ``download_file`` endpoint as ``build_only`` so ``url_for``119will work without a view function.120121.. code-block:: python122123 app.add_url_rule(124 "/uploads/<name>", endpoint="download_file", build_only=True125 )126127128Improving Uploads129-----------------130131.. versionadded:: 0.6132133So how exactly does Flask handle uploads? Well it will store them in the134webserver's memory if the files are reasonably small, otherwise in a135temporary location (as returned by :func:`tempfile.gettempdir`). But how136do you specify the maximum file size after which an upload is aborted? By137default Flask will happily accept file uploads with an unlimited amount of138memory, but you can limit that by setting the ``MAX_CONTENT_LENGTH``139config key::140141 from flask import Flask, Request142143 app = Flask(__name__)144 app.config['MAX_CONTENT_LENGTH'] = 16 * 1000 * 1000145146The code above will limit the maximum allowed payload to 16 megabytes.147If a larger file is transmitted, Flask will raise a148:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.149150.. admonition:: Connection Reset Issue151152 When using the local development server, you may get a connection153 reset error instead of a 413 response. You will get the correct154 status response when running the app with a production WSGI server.155156This feature was added in Flask 0.6 but can be achieved in older versions157as well by subclassing the request object. For more information on that158consult the Werkzeug documentation on file handling.159160161Upload Progress Bars162--------------------163164A while ago many developers had the idea to read the incoming file in165small chunks and store the upload progress in the database to be able to166poll the progress with JavaScript from the client. The client asks the167server every 5 seconds how much it has transmitted, but this is168something it should already know.169170An Easier Solution171------------------172173Now there are better solutions that work faster and are more reliable. There174are JavaScript libraries like jQuery_ that have form plugins to ease the175construction of progress bar.176177Because the common pattern for file uploads exists almost unchanged in allMerge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption53eef27
lines 178–180why, one step back178applications dealing with uploads, there are also some Flask extensions that179implement a full fledged upload mechanism that allows controlling which180file extensions are allowed to be uploaded.Merge remote-tracking branch 'origin/2.0.x'David Lordbefore adoption4240ace
lines 181–182why, one step back181182.. _jQuery: https://jquery.com/