File uploading is a common task in web apps. In this tutorial you learn how to do that with Python Flask. It is very simple to upload the file upload in the Flask file by the Flask file.

It requires an HTML form whose enctype property is set to "multipart/form-data" to publish the file to the URL.The URL handler extracts the file from the request.files [] object and saves it to the required location.

Related course: Python Flask: Create Web Apps with Flask

Upload file

Introduction

Each uploaded file is first saved on a temporary location on the server, and then will actually be saved to its final location.

The name of the target file can be hard-coded or available from the filename property of file] request.files object. However, it is recommended that the secure_filename() function be used to obtain a secure version of it.

The default upload folder path and maximum size of uploaded files can be defined in the configuration settings for the Flask object.

Define the path to the upload folder

1
app.config['UPLOAD_FOLDER']

Specifies the maximum size (in bytes) of the files to be uploaded

1
app.config['MAX_CONTENT_PATH']

The following code has a ‘/upload’ URL rule that displays’upload.html’ in the templates folder and the ‘/upload - file’ URL rule to invoke the upload () function to process the upload process.

‘upload.html’ has a file selector button and a submit button.

1
2
3
4
5
6
7
8
9
<html>
<body>
<form action = "http://localhost:5000/uploader" method = "POST"
enctype = "multipart/form-data">
<input type = "file" name = "file" />
<input type = "submit"/>
</form>
</body>
</html>

Python code

Once you’re selecting a file, click Submit. The form’s post method calls the ‘/upload_file’ URL. The underlying function uploader() performs a save operation.

Here’s the Python code for the Flask application.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)

@app.route('/upload')
def upload_file():
return render_template('upload.html')

@app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
f = request.files['file']
f.save(secure_filename(f.filename))
return 'file uploaded successfully'

if __name__ == '__main__':
app.run(debug = True)

Related course: Python Flask: Create Web Apps with Flask