English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask File Upload

Handling file uploads in Flask is very simple. It requires an enctype attribute set to 'multipart/form-HTML form with 'data', submit the form to the specified URL. The URL handler extracts the file from the request.files[] object and saves it to the required location.

Each uploaded file is first saved in a temporary location on the server and then saved to the final location. The target file name can be hardcoded or obtained from the filename attribute of the request.files [file] object. However, it is recommended to use the secure_filename() function to get its secure version.

You can define the default upload folder path and the maximum size of the uploaded file in the Flask object's configuration settings.

VariableDescription
app.config[‘UPLOAD_FOLDER’]Define the path of the upload folder
app.config[‘MAX_CONTENT_PATH’]Specify the maximum size of the file to be uploaded - in bytes

The following code has a URL: /upload rule, which displays the upload.html file in the templates folder, and the URL => calling the uploader() function to handle the upload process /upload-file rule.

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

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Example</title>
 </head>
    <body>
      <form action="http://localhost:5000/upload" method="POST" 
          enctype="multipart/form-data">
          <input type="file" name="file" />
          <input type="submit" value="Submit">/>
       </form>
    </body>
 </html>

You will see the following screenshot as shown -

Click after selecting a file Submit. The post method of the form calls the URL=> /The underlying function uploader() in upload_file. performs the file saving operation.

The following is the Python code for the Flask application.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by: www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template, request
 from werkzeug import secure_filename
 app = Flask(__name__)
 @app.route('/upload', methods=['GET', 'POST'])
 def upload_file():
     if request.method == 'POST':
         f = request.files['file']
         print(request.files)
         f.save(secure_filename(f.filename))
         return 'file uploaded successfully'
     else:
         return render_template('upload.html')
 if __name__ == '__main__':
     app.run(debug=True)

After running the program, execute the code above, select an image file, and then click upload to get the following result -