File uploading in Flask and how to do it?

In this tutorial, we are going to learn what is file uploading in Flask. We are also going to learn why is it essential to include this feature in our Flask webpage. Also, we are going to learn how to upload files through our webpage built-in Flask.

Flask – File uploading

Handling the uploads of files is quite easy though flask. All it needs is an HTML file having its ‘enctype’ attribute set to ‘multipart/form-data,’ then posting all the data to a specific URL. Then the URL handler fetches the requested files from request.files[] object and then saves it to the desired location.

Before a file is saved to its ultimate location, it is first saved in a temporary location on the server. We can include the name of the destination location by hard-coding it or can also be obtained from the filename property of the request.files[file] Object. However, it is recommended to use the secure_filename() function to generate a secure version of it.

It is possible in a Flask webpage to define the path of the default upload folder and also the maximum upload size for a specific file in configuration settings.

app.config[‘UPLOAD_FOLDER’] Sets the path for upload folder
app.config[‘MAX_CONTENT_PATH’] Specifies the maximum size of the file to be uploaded – in bytes

Example program to upload file in flask

The following piece of python code has a ‘/upload‘ URL that renders the ‘upload.html’ file present in the templates folder. It also contains the ‘/upload-file’ URL that calls the uploader() function that handles the upload process.

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)

The following piece of code is of ‘upload.html’ which contains a File chooser button and a Submit button alongside.

<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>

After uploading the file, click the Submit button. Then the ‘upload_file’ URL will get invoked by the form’s POST method. And the rest of the saving operation will be handled by the uploader() function.

Also learn:

Leave a Reply

Your email address will not be published. Required fields are marked *