Python 3 Script to Download File as Attachment in Browser Using HTML5 & Javascript Full Tutorial For Beginners

Python 3 Script to Download File as Attachment in Browser Using HTML5 & Javascript Full Tutorial For Beginners

 

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

 

 

This is a simple input text file

 

 

Now just create an app.py file and copy paste the following code

 

app.py

 

 

# 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

READ  Python 3 Tkinter Multiplayer Online Chess Board + (Computer AI) Modern Color Game GUI Desktop App Full Project For Beginners

 

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

 

 

<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

READ  Python 3 Datetime Library Script to Convert Current Date Time to Timezone Full Project For Beginners

 

 

Leave a Reply