Skip to content
Myr

send_from_directory > SharedDataMiddleware

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 16e4d5a · Browse files · 1 file+15 added−8 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+15 added−8 removed

  • other:+15 added−8 removed

1 file+15 added−8 removed

modified:docs/patterns/fileuploads.rst+15 added-8 removed
26 unmodified lines
27 UPLOAD_FOLDER = '/path/to/the/uploads'28 ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])2930 app = Flask(__name__)31 app.add_url_rule('/uploads/<filename>', 'uploaded_file',32 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 the
62 unmodified lines
9798 >>> secure_filename('../../../../home/username/.bashrc')99 'home_username_.bashrc'100103Now if we run that application, you will notice that uploading works, but104you won't actually see that uploaded file. Well, you would have to105configure the server to serve that file for you. This is not handy for106development situations or when you are just too lazy to properly set up107the server. Would be nice to have the files still be available in that108situation, and that is really easy to do, just hook in a middleware::101Now one last thing is missing: the serving of the uploaded files. As of102Flask 0.5 we can use a function that does that for us::103104 from flask import send_from_directory105106 @app.route('/uploads/<filename>')107 def uploaded_file(filename):108 return send_from_directory(app.config['UPLOAD_FOLDER'],109 filename)110111Alternatively you can register `uploaded_file` as `build_only` rule and112use the :class:`~werkzeug.SharedDataMiddleware`. This also works with113older versions of Flask::114115 from werkzeug import SharedDataMiddleware116 app.add_url_rule('/uploads/<filename>', 'uploaded_file',117 build_only=True)118 app.wsgi_app = SharedDataMiddleware(app.wsgi_app, {119 '/uploads': UPLOAD_FOLDER120 })121
46 unmodified lines