Welcome folks today in this blog post we will downloading file as an attachment
in browser using html5
in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries using the pip
command as shown below
pip install flask
Now we will see the below directory structure of the flask
app as shown below
And now you need to make an app.py
file and copy paste the below code
app.py
1 2 3 4 5 6 7 8 9 10 11 |
from flask import Flask,render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__": app.run(debug=True) |
As you can see we are importing the flask
library and starting the app at port number 5000. And also we are rendering the index.html
template file whenever we go to the /
route. We are using the render_template()
for this purpose. And now we need to make this template inside the templates
folder
templates/index.html
1 2 3 |
<h2>Download the File as an Attachment</h2> <a href="{{url_for('download_file')}}">Download File</a> |
As you can see we are simply have an anchor
element where we are allowing the user to download
the file as an attachment. Now we have attached the url_for
directive to the href attribute. Now we need to create the download_file
method as shown below
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
from flask import Flask,render_template,send_file app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/download_file') def download_file(): path = "image.png" return send_file(path,as_attachment=True) if __name__ == "__main__": app.run(debug=True) |
As you can see we have defined another get
route to download the file as an attachment and inside it we are importing the send_file()
method of flask to download the file and then we are passing the path
of the file to be downloaded and also providing the second boolean
parameter as_attachment
to True.