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 c21caa5 · 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
Provenance
- Commit
85d4307- Tree
8403f6c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
c21caa5
1 file changed+158 added−0 removed
added:docs/patterns/fileuploads.rst+158 added
1+Uploading Files2+===============3+4+Ah yes, the good old problem of file uploads. The basic idea of file5+uploads is actually quite simple. It basically works like this:6+7+1. A ``<form>`` tag is marked with ``enctype=multipart/form-data``8+ and an ``<input type=file>`` is placed in that form.9+2. The application accesses the file from the :attr:`~flask.request.files`10+ dictionary on the request object.11+3. use the :meth:`~werkzeug.FileStorage.save` method of the file to save12+ the file permanently somewhere on the filesystem.13+14+A Gentle Introduction15+---------------------16+17+Let's start with a very basic application that uploads a file to a18+specific upload folder and displays a file to the user. Let's look at the19+bootstrapping code for our application::20+21+ import os22+ from flask import Flask, request, redirect, url_for23+ from werkzeug import secure_filename24+25+ UPLOAD_FOLDER = '/path/to/the/uploads'26+ ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])27+28+ app = Flask(__name__)29+ app.add_url_rule('/uploads/<filename>', 'uploaded_file',30+ build_only=True)31+32+So 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 a36+URL rule by hand to the application. Now usually we're not doing that, so37+why here? The reasons is that we want the webserver (or our development38+server) to serve these files for us and so we only need a rule to generate39+the URL to these files.40+41+Why do we limit the extensions that are allowed? You probably don't want42+your users to be able to upload everything there if the server is directly43+sending out the data to the client. That way you can make sure that users44+are not able to upload HTML files that would cause XSS problems. Also45+make sure to disallow `.php` files if the server executes them, but who46+has PHP installed on his server, right? :)47+48+Next the functions that check if an extension is valid and that uploads49+the file and redirects the user to the URL for the uploaded file::50+51+ def allowed_file(filename):52+ return '.' in filename and \53+ filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS54+55+ @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+ '''73+74+So what does that :func:`~werkzeug.secure_filename` function actually do?75+Now the problem is that there is that principle called "never trust user76+input". This is also true for the filename of an uploaded file. All77+submitted form data can be forged, and filenames can be dangerous. For78+the moment just remember: always use that function to secure a filename79+before storing it directly on the filesystem.80+81+.. admonition:: Information for the Pros82+83+ 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::87+88+ filename = "../../../../home/username/.bashrc"89+90+ 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 :)95+96+ Now let's look how that function works:97+98+ >>> secure_filename('../../../../home/username/.bashrc')99+ 'home_username_.bashrc'100+101+Now if we run that application, you will notice that uploading works, but102+you won't actually see that uploaded file. Well, you would have to103+configure the server to serve that file for you. This is not handy for104+development situations or when you are just too lazy to properly set up105+the server. Would be nice to have the files still be available in that106+situation, and that is really easy to do, just hook in a middleware::107+108+ from werkzeug import SharedDataMiddleware109+ app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {110+ '/uploads': UPLOAD_FOLDER111+ })112+113+If you now run the application everything should work as expected.114+115+116+Improving Uploads117+-----------------118+119+So how exactly does Flask handle uploads? Well it will store them in the120+webserver's memory if the files are reasonable small otherwise in a121+temporary location (as returned by :func:`tempfile.gettempdir`). But how122+do you specify the maximum file size after which an upload is aborted? By123+default Flask will happily accept file uploads to an unlimited amount of124+memory, but you can limit that by subclassing the request and overriding125+the Werkzeug provided :attr:`~werkzeug.BaseRequest.max_form_memory_size`126+attribute::127+128+ from flask import Flask, Request129+130+ class LimitedRequest(Request):131+ max_form_memory_size = 16 * 1024 * 1024132+133+ app = Flask(__name__)134+ app.request_class = LimitedRequest135+136+The code above will limited the maximum allowed payload to 16 megabytes.137+If a larger file is transmitted, Flask will raise an138+:exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception.139+140+141+Upload Progress Bars142+--------------------143+144+A while ago many developers had the idea to read the incoming file in145+small chunks and store the upload progress in the database to be able to146+poll the progress with JavaScript from the client. Long story short: the147+client asks the server every 5 seconds how much he has transmitted148+already. Do you realize the irony? The client is asking for something he149+should already know.150+151+Now there are better solutions to that work faster and more reliable. The152+web changed a lot lately and you can use HTML5, Java, Silverlight or Flash153+to get a nicer uploading experience on the client side. Look at the154+following libraries for some nice examples how to do that:155+156+- `Plupload <http://www.plupload.com/>`_ - HTML5, Java, Flash157+- `SWFUpload <http://www.swfupload.org/>`_ - Flash158+- `JumpLoader <http://jumploader.com/>`_ - Java