Raise a File Download Dialog Box in Python

Raising a File Download Dialog Box for end-user to download files like pdf, media-objects, documents, etc in Python can be done by the use of HTTP Header. It comes in handy where there is a need to develop a feature where instead of showing the files in the browser, the file contains is automatically downloaded.

For instance, if you need a file say (GeeksForGeeks.txt) to be downloaded on click of a link from the database the code would somewhat look like below:

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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()

chevron_right


If you just run the script it will just read the original file as below:

Note: One needs to make sure the file to be downloaded is in the same directory as the Python script.

Using the script in your application:
The below code is a simple example of the use of the above script in an application:

filter_none

edit
close

play_arrow

link
brightness_4
code

<html>
<body>
<form enctype = "multipart/form-data" action = "python_script.py" method = "get">
<p>File link:<a href="GeeksForGeeks.txt" download>Click Here</a></p>
</form>
</body>
</html>                    

chevron_right


Output:

On click of the “Click Here” link the download box would pop up and start downloading the file.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.