0
0
Flaskframework~5 mins

File download responses in Flask

Choose your learning style9 modes available
Introduction

File download responses let your web app send files to users so they can save them on their devices.

When you want users to download reports or documents your app creates.
When providing images, PDFs, or other files for users to save.
When letting users download backups or exported data.
When sharing software or updates as downloadable files.
When sending any file that should not just display in the browser but be saved.
Syntax
Flask
from flask import send_file

@app.route('/download')
def download():
    return send_file('path/to/file', as_attachment=True, download_name='filename.ext')

send_file is the main function to send files in Flask.

Use as_attachment=True to force the browser to download instead of display.

Examples
Sends a PDF file named 'report.pdf' for download.
Flask
return send_file('files/report.pdf', as_attachment=True, download_name='report.pdf')
Sends an image file that the browser may display instead of download.
Flask
return send_file('images/photo.jpg', mimetype='image/jpeg')
Sends a CSV file for download using the original filename.
Flask
return send_file('files/data.csv', as_attachment=True)
Sample Program

This Flask app has a home page with a link. Clicking it downloads 'sample.txt' as 'example.txt'.

Flask
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/')
def home():
    return '<a href="/download">Download File</a>'

@app.route('/download')
def download():
    # Sends a text file for download with a custom name
    return send_file('sample.txt', as_attachment=True, download_name='example.txt')

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

Make sure the file path is correct and accessible by your Flask app.

Use download_name to set the filename users see when saving.

For large files, consider using send_from_directory or streaming responses.

Summary

Use send_file to send files from Flask to users.

Set as_attachment=True to force download instead of display.

Customize the saved filename with download_name.