Skip to content
Myr

Added missing file (fileupload docs)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 0c54d0a · Browse files · 1 file+158 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+158 added−0 removed

  • other:+158 added−0 removed

1 file+158 added−0 removed

added:docs/patterns/fileuploads.rst+158 added
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.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, request, redirect, url_for23 from werkzeug import secure_filename2425 UPLOAD_FOLDER = '/path/to/the/uploads'26 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])2728 app = Flask(__name__)29 app.add_url_rule('/uploads/<filename>', 'uploaded_file',30 build_only=True)3132So first we need a couple of imports. Most should be straightforward, the33:func:`werkzeug.secure_filename` is explained a little bit later. The34`UPLOAD_FOLDER` is where we will store the uploaded files and the35`ALLOWED_EXTENSIONS` is the set of allowed file extensions. Then we add a36URL rule by hand to the application. Now usually we're not doing that, so37why here? The reasons is that we want the webserver (or our development38server) to serve these files for us and so we only need a rule to generate39the URL to these files.4041Why do we limit the extensions that are allowed? You probably don't want42your users to be able to upload everything there if the server is directly43sending out the data to the client. That way you can make sure that users44are not able to upload HTML files that would cause XSS problems. Also45make sure to disallow `.php` files if the server executes them, but who46has PHP installed on his server, right? :)4748Next the functions that check if an extension is valid and that uploads49the file and redirects the user to the URL for the uploaded file::5051 def allowed_file(filename):52 return '.' in filename and \53 filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS5455 @app.route('/')56 def upload_file():57 if request.method == 'POST':58 file = request.files['file']59 if file and allowed_file(file.filename):60 filename = secure_filename(file.filename)61 file.save(os.path.join(UPLOAD_FOLDER, filename))62 return redirect(url_for('uploaded_file',63 filename=filename))64 return '''65 <!doctype html>66 <title>Upload new File</title>67 <h1>Upload new File</h1>68 <form action="" method=post enctype=multipart/form-data>69 <p><input type=file name=file>70 <input type=submit value=Upload>71 </form>72 '''7374So what does that :func:`~werkzeug.secure_filename` function actually do?75Now the problem is that there is that principle called "never trust user76input". This is also true for the filename of an uploaded file. All77submitted form data can be forged, and filenames can be dangerous. For78the moment just remember: always use that function to secure a filename79before storing it directly on the filesystem.8081.. admonition:: Information for the Pros8283 So you're interested in what that :func:`~werkzeug.secure_filename`84 function does and what the problem is if you're not using it? So just85 imagine someone would send the following information as `filename` to86 your application::8788 filename = "../../../../home/username/.bashrc"8990 Assuming the number of ``../`` is correct and you would join this with91 the `UPLOAD_FOLDER` the user might have the ability to modify a file on92 the server's filesystem he should not modify. This does require some93 knowledge about how the application looks like, but trust me, hackers94 are patient :)9596 Now let's look how that function works:9798 >>> secure_filename('../../../../home/username/.bashrc')99 'home_username_.bashrc'100101Now if we run that application, you will notice that uploading works, but102you won't actually see that uploaded file. Well, you would have to103configure the server to serve that file for you. This is not handy for104development situations or when you are just too lazy to properly set up105the server. Would be nice to have the files still be available in that106situation, and that is really easy to do, just hook in a middleware::107108 from werkzeug import SharedDataMiddleware109 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {110 '/uploads': UPLOAD_FOLDER111 })112113If you now run the application everything should work as expected.114115116Improving Uploads117-----------------118119So how exactly does Flask handle uploads? Well it will store them in the120webserver's memory if the files are reasonable small otherwise in a121temporary location (as returned by :func:`tempfile.gettempdir`). But how122do you specify the maximum file size after which an upload is aborted? By123default Flask will happily accept file uploads to an unlimited amount of124memory, but you can limit that by subclassing the request and overriding125the Werkzeug provided :attr:`~werkzeug.BaseRequest.max_form_memory_size`126attribute::127128 from flask import Flask, Request129130 class LimitedRequest(Request):131 max_form_memory_size = 16 * 1024 * 1024132133 app = Flask(__name__)134 app.request_class = LimitedRequest135136The code above will limited the maximum allowed payload to 16 megabytes.137If a larger file is transmitted, Flask will raise an138:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.139140141Upload Progress Bars142--------------------143144A while ago many developers had the idea to read the incoming file in145small chunks and store the upload progress in the database to be able to146poll the progress with JavaScript from the client. Long story short: the147client asks the server every 5 seconds how much he has transmitted148already. Do you realize the irony? The client is asking for something he149should already know.150151Now there are better solutions to that work faster and more reliable. The152web changed a lot lately and you can use HTML5, Java, Silverlight or Flash153to get a nicer uploading experience on the client side. Look at the154following libraries for some nice examples how to do that:155156- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash157- `SWFUpload <http://www.swfupload.org/>`_ - Flash158- `JumpLoader <http://jumploader.com/>`_ - Java