Welcome folks today in this post we will be downloading file
as attachment in browser in html5 and javascript. All the source code of the application will be given below.
Get Started
In order to get started you need to create a text file
called input.txt
and copy paste the following code
input.txt
1 |
This is a simple input text file |
Now just create an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# python_script.py # HTTP Header print ("Content-Type:application/octet-stream; name = \"FileName\"\r\n") print ("Content-Disposition: attachment; filename = \"FileName\"\r\n\n") # Original File my_file = open("GeeksForGeeks.txt", "rb") # read the file content text = my_file.read(); print (text) # Close opend file my_file.close() |
Now if you execute app.py
by typing the below command
python app.py
So you can say it is displaying
the contents of the text file inside the console. So we want to download this text file instead inside the browser.
For this we need to create an index.html
file inside the same directory and copy paste the following code
index.html
1 2 3 4 5 6 7 |
<html> <body> <form enctype = "multipart/form-data" action = "python_script.py" method = "get"> <p>File link:<a href="input.txt" download>Click Here</a></p> </form> </body> </html> |
So now if you open index.html
file inside the browser you will see the following output which is shown below
Now if you click the hyerlink then the text
file will be downloaded as an attachment as shown below