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 | <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 | from flask import Flask, render_template, request |
Related course: Python Flask: Create Web Apps with Flask