How To Raise a "File Download" Dialog Box in Python?

Sometimes, you want to provide a download link that triggers a "File Download" dialog box instead of displaying the file content directly in the browser. This can be achieved by setting specific HTTP headers that instruct the browser to treat the response as a downloadable file.

Basic File Download Example

Here's how to create a simple file download response using Python CGI ?

#!/usr/bin/python3
import sys

# Set HTTP headers for file download
print("Content-Type: application/octet-stream; name="example.txt"")
print("Content-Disposition: attachment; filename="example.txt"")
print()  # Empty line to separate headers from content

# Read and output file content
try:
    with open("example.txt", "rb") as file:
        content = file.read()
        sys.stdout.buffer.write(content)
except FileNotFoundError:
    print("Error: File not found")

Understanding the Headers

Two key HTTP headers control the download behavior ?

  • Content-Type: Set to application/octet-stream to indicate binary data
  • Content-Disposition: Set to attachment with a filename to trigger download

Text File Download

#!/usr/bin/python3

# Headers for text file download
print("Content-Type: text/plain; charset=utf-8")
print("Content-Disposition: attachment; filename="data.txt"")
print()

# Sample text content
content = """Sample data for download
Line 2: Hello World
Line 3: Python file download example"""

print(content)

Web Framework Approach

For modern web applications, use frameworks like Flask ?

from flask import Flask, send_file, make_response
import io

app = Flask(__name__)

@app.route('/download/<filename>')
def download_file(filename):
    # Create file content
    content = "This is downloadable content"
    
    # Create in-memory file
    file_obj = io.BytesIO(content.encode())
    
    # Create response with download headers
    response = make_response(file_obj.getvalue())
    response.headers['Content-Type'] = 'application/octet-stream'
    response.headers['Content-Disposition'] = f'attachment; filename={filename}'
    
    return response

if __name__ == '__main__':
    app.run(debug=True)

Content Type Options

File Type Content-Type Use Case
Any file application/octet-stream Generic binary download
Text files text/plain Plain text downloads
CSV files text/csv Spreadsheet data
JSON files application/json API data exports

Conclusion

Use Content-Disposition: attachment header to trigger file downloads. Set appropriate Content-Type based on your file format. Modern web frameworks provide built-in methods for easier file serving.

Updated on: 2026-03-25T07:52:01+05:30

602 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements