How to Upload and Make a Download Button Flask Python

Flask is one of the well-nigh popular frameworks for backend development. It is a microframework based on the python programming linguistic communication. Instead, a micro-framework Flask is very powerful and is highly extensible. Since Python is popular for Machine Learning and Data Science, Flask is hugely used to serve Machine Learning and Data Scientific discipline related apps. In this tutorial, we will acquire how to create a file uploader and file downloader using Flask.

File Uploading and downloading is an important task for a website. For instance, assume that we were building a site that takes some images from user uploads and converts them into a unmarried PDF. Subsequently converting the images into PDF, the website serves the PDF to the user. We need to larn to upload and download files using server-side frameworks like Flask in such a scenario.

Flask installation

We can install Flask hands with the help of the pip tool. PIP is a command-line tool, and it is the default package manager for managing python packages. To install the Flask framework, we need to run the following command in the terminal.

On running the above command in the final, we will take Flask installed in our system. We tin can bank check our installation by opening the python shell and importing the Flask library. Encounter the below image for illustration.

checking the installation of flask by importing the library
checking the installation of Flask by importing the library

Now, let us create our file uploader using Flask.

Creating the File Uploader

The first step while creating our file uploader is to build the Html grade. To publish the file, we need to fix the enctype belongings of the form to "multipart/form-information". First, create a templates folder in the current directory. Afterward that, create a file with the name upload.html in the templates folder and copy the post-obit HTML code into the upload.html file.

<!DOCTYPE html> <html lang="en">   <head>     <meta charset="UTF-8" />     <meta http-equiv="X-UA-Compatible" content="IE=edge" />     <meta name="viewport" content="width=device-width, initial-scale=1.0" />     <title>File uploader</title>   </head>   <body>     <form       action="http://localhost:5000/upload"       method="Postal service"       enctype="multipart/form-information"     >       <input type="file" proper name="file" />       <input type="submit" />     </form>   </body> </html>

Subsequently creating the HTML template for the file uploader, now, in the principal directory, create a file with the name app.py. The app.py file contains the code for our Flask application. We will likewise utilise the secure_filename() part of the werkzeug module. The secure_filename() module checks for vulnerability in the uploaded files and protects the server from dangerous files. Copy the following code into the app.py file.

# importing the required libraries from flask import Flask, render_template, request from werkzeug.utils import secure_filename # initialising the flask app app = Flask(__name__)  # The path for uploading the file @app.route('/') def upload_file():    return render_template('upload.html')  @app.route('/upload', methods = ['Get', 'Post']) def uploadfile():    if asking.method == 'Postal service': # check if the method is postal service       f = request.files['file'] # get the file from the files object       f.save(secure_filename(f.filename)) # this volition secure the file       render 'file uploaded successfully' # Display thsi message after uploading 		 if __name__ == '__main__':    app.run() # running the flask app

In the above lawmaking, we first imported the required modules to our code. After importing the required modules, we initialize the Flask app by calling the Flask() constructor. Adjacent, we use python decorators to define the routes for our Flask app and serve the HTML template that nosotros created. Side by side, nosotros use python decorators to accept the post asking for the file and save the file.

You tin run the above lawmaking past merely typing python app.py in the terminal. Nosotros will see something as shown in the beneath image while running the above code.

starting the flask server
starting the Flask server

Now, visit the URL http://127.0.0.1:5000/ where you will see a file uploader as shown in the below image.

a simple upload webpage in flask
a simple upload webpage in Flask

Upload a sample file by choosing a file and clicking the submit push button. After submitting the file, we will get a message showing that the file has been successfully uploaded. We tin check the file in the server past visiting the root directory.

Configuring the upload folder

We created a file uploader that saves the uploaded file in the root directory. We can likewise configure the directory for saving the file past configuring the app.config['UPLOAD_FOLDER'] variable. At showtime, the uploaded file is saved into a temporary location, and then it moves to the terminal location. The following lawmaking shows how to configure the upload directory.

# importing the required libraries import os from flask import Flask, render_template, request from werkzeug.utils import secure_filename  # initialising the flask app app = Flask(__name__)  # Creating the upload folder upload_folder = "uploads/" if not os.path.exists(upload_folder):    os.mkdir(upload_folder)  app.config['UPLOAD_FOLDER'] = upload_folder  # The path for uploading the file @app.road('/') def upload_file():    render render_template('upload.html')  @app.road('/upload', methods = ['Go', 'Post']) def uploadfile():    if request.method == 'Mail': # bank check if the method is postal service       f = request.files['file'] # go the file from the files object       # Saving the file in the required destination       f.relieve(os.path.join(app.config['UPLOAD_FOLDER'] ,secure_filename(f.filename))) # this volition secure the file       return 'file uploaded successfully' # Brandish thsi bulletin after uploading 		 if __name__ == '__main__':    app.run() # running the flask app

In the above lawmaking, we utilize the Bone module of python to create a directory and saves every uploaded file to the created directory. If we restart the server and upload a file to the server, the file will be uploaded to the created directory instead of the root directory.

Configuring the maximum file size

We tin also configure the maximum upload size of the file. This is of import because if the file is also large for the server, then the site may crash. So, nosotros demand to always limit the upload size of the file according to our server. To configure the maximum file size, we need to prepare the app.config['MAX_CONTENT_LENGTH'] variable to the maximum size of the file in bytes. For example, if nosotros want to limit the maximum size of the file to one Mb, we need to add the following line of lawmaking in our program.

app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024

After setting the maximum file size of the file in our python program, if we upload a file having a size of more than 1 Mb, so we will get the error every bit shown in the beneath paradigm.

setting the maximum upload size of a file in flask
setting the maximum upload size of a file in Flask

Configuring the immune file extensions

While building a file uploader using Flask, nosotros can also configure the file extensions that nosotros want to upload. To configure the allowed file extensions, we need to create a list of allowed extensions and cheque the uploaded file extension in the list. The below code shows a applied analogy of the method.

# importing the required libraries import bone from flask import Flask, render_template, request from werkzeug.utils import secure_filename  # initialising the flask app app = Flask(__name__)  # Creating the upload folder upload_folder = "uploads/" if not os.path.exists(upload_folder):    os.mkdir(upload_folder)  # Max size of the file app.config['MAX_CONTENT_LENGTH'] = i * 1024 * 1024  # Configuring the upload binder app.config['UPLOAD_FOLDER'] = upload_folder  # configuring the allowed extensions allowed_extensions = ['jpg', 'png', 'pdf']  def check_file_extension(filename):     return filename.split('.')[-1] in allowed_extensions  # The path for uploading the file @app.route('/') def upload_file():    return render_template('upload.html')  @app.route('/upload', methods = ['GET', 'Postal service']) def uploadfile():    if asking.method == 'POST': # check if the method is post       f = request.files['file'] # get the file from the files object       # Saving the file in the required destination       if check_file_extension(f.filename):          f.salvage(os.path.bring together(app.config['UPLOAD_FOLDER'] ,secure_filename(f.filename))) # this will secure the file          render 'file uploaded successfully' # Display thsi bulletin after uploading       else:          render 'The file extension is not allowed' 		 if __name__ == '__main__':    app.run() # running the flask app

In the above code, we create a function that will cheque the uploaded file extension and compare it with the allowed extensions. If nosotros upload a file that does non have the extension of PDF, JPG, PNG, so the server will testify the bulletin as shown in the below image.

restricitng the upload of certain file extension in flask
restricting the upload of certain file extensions in Flask

Multiple file uploading using Flask

Till now, nosotros have seen how to upload a single file to our server. But sometimes, we also desire to upload multiple files to the server. To upload multiple files to our server offset, nosotros need to add multiple="true" as an attribute to the input element of the Html class. Run into the beneath lawmaking for analogy.

<!DOCTYPE html> <html lang="en">   <head>     <meta charset="UTF-eight" />     <meta http-equiv="X-UA-Uniform" content="IE=edge" />     <meta proper noun="viewport" content="width=device-width, initial-scale=ane.0" />     <title>File uploader</title>   </head>   <body>     <class       action="http://localhost:5000/upload"       method="POST"       enctype="multipart/form-data"     >       <input type="file" name="files", multiple="true" />       <input type="submit" />     </form>   </trunk> </html>

After creating the Html course, nosotros need to make some changes to our Flask application file. Start, copy the following Python lawmaking into your Flask app file.

# importing the required libraries import os from flask import Flask, render_template, request from werkzeug.utils import secure_filename  # initialising the flask app app = Flask(__name__)  # Creating the upload binder upload_folder = "uploads/" if non os.path.exists(upload_folder):    os.mkdir(upload_folder)  # Configuring the upload binder app.config['UPLOAD_FOLDER'] = upload_folder  # configuring the allowed extensions allowed_extensions = ['jpg', 'png', 'pdf']  def check_file_extension(filename):     return filename.split('.')[-ane] in allowed_extensions  # The path for uploading the file @app.route('/') def upload_file():    return render_template('upload.html')  @app.route('/upload', methods = ['GET', 'Postal service']) def uploadfile():    if request.method == 'POST': # check if the method is mail       files = request.files.getlist('files') # get the file from the files object       print(files)       for f in files:          impress(f.filename)          # Saving the file in the required destination          if check_file_extension(f.filename):             f.relieve(os.path.join(app.config['UPLOAD_FOLDER'] ,secure_filename(f.filename))) # this volition secure the file        return 'file uploaded successfully' # Brandish thsi message after uploading 		 if __name__ == '__main__':    app.run() # running the flask app

In the to a higher place code, we use python for loop to iterate over the listing of files and and then salve each file one by one. We tin cull multiple files at present and upload them at once to the server.

Serving the files

We accept seen how to upload files using Flask, but sometimes we also want to serve a file to the user. To serve a file from our server to the user, we need to utilise the send_file() function of the Flask. First, create an HTML template in the templates binder, named the file download.html, and add the following code into the Html file.

<!DOCTYPE html> <html lang="en">   <caput>     <meta charset="UTF-viii" />     <meta http-equiv="X-UA-Uniform" content="IE=edge" />     <meta name="viewport" content="width=device-width, initial-scale=one.0" />     <title>File Downloader</title>   </head>   <body>     <a href="/download"><button grade='btn btn-default'>Download</button></a>   </body> </html>

The in a higher place HTML lawmaking volition create a button with the characterization Download and add together a link to the button that refers to the route /download. At present, we need to create our app.py file. In our app.py, we need to use the send_file() function and pass the file's path to it. So, copy and paste the following code in the app.py file.

# importing the required libraries import bone from flask import Flask, render_template, request, send_file  # initialising the flask app app = Flask(__name__)  # displaying the HTML template at the dwelling url @app.road('/') def index():    render render_template('download.html')  # Sending the file to the user @app.route('/download') def download():    return send_file('sample.pdf', as_attachment=True)  if __name__ == '__main__':    app.run() # running the flask app

Afterward copying the higher up lawmaking, run the lawmaking by typing the control python app.py. If everything works fine and the server starts without any problem, we have created our file downloader. At present, visit the URL http://127.0.0.1:5000/, you will see something equally shown in the below image.

creating a file downloader using flask
creating a file downloader using Flask

If you click the download button present in the URL, then the file will outset downloading. For the in a higher place code to work properly, we demand a file with the name sample.pdf in the app directory.

Decision

In this tutorial, we learned to create a file uploader and file downloader using the Flask library. In addition, we have seen how to configure the max size and extension of the file upload. Yous may likewise want to see our pace-by-step guide on creating a Flask app in python.

stubbswaspupperen.blogspot.com

Source: https://www.codeunderscored.com/upload-download-files-flask/

0 Response to "How to Upload and Make a Download Button Flask Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel