File uploading is a typical task in web apps. Taking care of file upload in Flask is simple all we need is to have an HTML form with the encryption set to multipart/form information to publish the file into the URL. The server-side flask script brings the file from the request object utilizing the request.files[] Object. On effectively uploading the file, it is saved to the ideal location on the server.
Install the Flask by writing the command in terminal:
pip install flask
Stepwise Implementation
Step 1: A new folder “file uploading” should be created. Create the folders “templates” and “main.py” in that folder, which will store our HTML files and serve as the location for our Python code.
Step 2: For the front end, we must first develop an HTML file where the user can select a file and upload it by clicking the upload buttons. The user will click the submit button after choosing the file from their local computer in order to transmit it to the server.
Index.html
HTML
< html > < head > < title >upload the file : GFG</ title > </ head > < body > < form action = "/success" method = "post" enctype = "multipart/form-data" > < input type = "file" name = "file" /> < input type = "submit" value = "Upload" > </ form > </ body > </ html > |
Step 3: We must make another HTML file just for acknowledgment. Create a file inside the templates folder called “Acknowledgement.html” to do this. This will only be triggered if the file upload went smoothly. Here, the user will receive a confirmation.
Acknowledgement.html
HTML
< html > < head > < title >success</ title > </ head > < body > < p >File uploaded successfully</ p > < p >File Name: {{name}}</ p > </ body > </ html > |
Step 4: Now inside the ‘main.py’ write the following codes. The name of the objective file can be obtained by using the following code and then we will save the uploaded file to the root directory.
main.py
Python3
from distutils.log import debug from fileinput import filename from flask import * app = Flask(__name__) @app .route( '/' ) def main(): return render_template( "index.html" ) @app .route( '/success' , methods = [ 'POST' ]) def success(): if request.method = = 'POST' : f = request.files[ 'file' ] f.save(f.filename) return render_template( "Acknowledgement.html" , name = f.filename) if __name__ = = '__main__' : app.run(debug = True ) |
Output:
Run the following command in your terminal.
python main.py
Step 5: Now, to check if it is correctly working or not go to the folder where ‘main.py‘. Check in that folder you will find the files there.