<form>
tag is marked with enctype=multipart/form-data
and an <inputtype=file>
is placed in that form.files
dictionary on the request object.save()
method of the file to savethe file permanently somewhere on the filesystem.werkzeug.secure_filename()
is explained a little bit later. TheUPLOAD_FOLDER
is where we will store the uploaded files and theALLOWED_EXTENSIONS
is the set of allowed file extensions..php
files if the serverexecutes them, but who has PHP installed on their server, right? :)secure_filename()
function actually do?Now the problem is that there is that principle called “never trust userinput”. This is also true for the filename of an uploaded file. Allsubmitted form data can be forged, and filenames can be dangerous. Forthe moment just remember: always use that function to secure a filenamebefore storing it directly on the filesystem.secure_filename()
function does and what the problem is if you’re not using it? So justimagine someone would send the following information as filename toyour application:./
is correct and you would join this withthe UPLOAD_FOLDER
the user might have the ability to modify a file onthe server’s filesystem he or she should not modify. This does require someknowledge about how the application looks like, but trust me, hackersare patient :)upload_file()
we redirect the user tourl_for('uploaded_file',filename=filename)
, that is, /uploads/filename
.So we write the uploaded_file()
function to return the file of that name. Asof Flask 0.5 we can use a function that does that for us:SharedDataMiddleware
. This also works witholder versions of Flask:tempfile.gettempdir()
). But howdo you specify the maximum file size after which an upload is aborted? Bydefault Flask will happily accept file uploads to an unlimited amount ofmemory, but you can limit that by setting the MAX_CONTENT_LENGTH
config key:RequestEntityTooLarge
exception.