fileuploads.rst
This file
Path
docs/patterns/fileuploads.rst
184 lines · 7.4 KiB
Last changed by
Restructure Upload Progress BarsMarkus Unterwaditzerbefore adoption0a492a0
History of this fileTake it
The walk stopped after 200 commits: lines older than 8d3ee01 point at it.
Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 1–34why, one step back1.. _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, 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. TheMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 35why, one step back35``UPLOAD_FOLDER`` is where we will store the uploaded files and theMerge remote-tracking branch 'sourya/master'Markus Unterwaditzerbefore adoption9a61e7d
line 36why, one step back36``ALLOWED_EXTENSIONS`` is the set of allowed file extensions.Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 37–41why, one step back3738Why 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 (seeMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 42why, one step back42:ref:`xss`). Also make sure to disallow ``.php`` files if the serverMerge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 43–96why, one step back43executes them, but who has PHP installed on his 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] 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 a 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 action="" method=post enctype=multipart/form-data>75 <p><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 withMerge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 97why, one step back97 the ``UPLOAD_FOLDER`` the user might have the ability to modify a file onMerge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 98–106why, one step back98 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'106Merge remote-tracking branch 'sourya/master'Markus Unterwaditzerbefore adoption9a61e7d
lines 107–111why, one step back107Now one last thing is missing: the serving of the uploaded files. In the 108:func:`upload_file()` we redirect the user to 109``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::Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
lines 112–173why, one step back112113 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 limited the maximum allowed payload to 16 megabytes.153If a larger file is transmitted, Flask will raise an154:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.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. Long story short: the167client asks the server every 5 seconds how much it has transmitted168already. Do you realize the irony? The client is asking for something it169should already know.170171An Easier Solution172------------------173Restructure Upload Progress BarsMarkus Unterwaditzerbefore adoption0a492a0
lines 174–177why, one step back174Now there are better solutions that work faster and are more reliable. There175are JavaScript libraries like jQuery_ that have form plugins to ease the176construction of progress bar.177Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 178why, one step back178Because the common pattern for file uploads exists almost unchanged in allRestructure Upload Progress BarsMarkus Unterwaditzerbefore adoption0a492a0
lines 179–181why, one step back179applications dealing with uploads, there is also a Flask extension called180`Flask-Uploads`_ that implements a full fledged upload mechanism with white and181blacklisting of extensions and more.Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 182why, one step back182Restructure Upload Progress BarsMarkus Unterwaditzerbefore adoption0a492a0
line 183why, one step back183.. _jQuery: https://jquery.com/Merge pull request #1132 from nicorevin/update_linksDaniel Neuhäuserbefore adoption8d3ee01
line 184why, one step back184.. _Flask-Uploads: http://pythonhosted.org/Flask-Uploads/