Flask Send File To Download [updated] -
For files stored permanently on your server's filesystem, map user routes directly to the asset path using send_from_directory .
import io from flask import Flask, send_file app = Flask(__name__) @app.route('/export-csv') def export_csv(): # Generate CSV data dynamically in memory proxy = io.StringIO() proxy.write("id,username,email\n") proxy.write("1,johndoe,john@example.com\n") proxy.write("2,janedoe,jane@example.com\n") # Reset pointer to the beginning of the stream mem_file = io.BytesIO(proxy.getvalue().encode('utf-8')) return send_file( mem_file, mimetype='text/csv', as_attachment=True, download_name='user_export.csv' ) Use code with caution. Production & Security Considerations 1. Guarding Against Path Traversal flask send file to download
Flask provides two primary functions within its flask module to handle file transmission: send_file() and send_from_directory() . Understanding the distinction between them is crucial for application security. 1. send_file() For files stored permanently on your server's filesystem,
This is the foundational function used to send the contents of a file from a specified path to the client. Guarding Against Path Traversal Flask provides two primary
Instead, offload file delivery to a production web server like Nginx or Apache using the X-Sendfile protocol. Flask authenticates the request and passes a special header to Nginx, which then streams the file to the client directly from disk at native C-speeds. To enable this, configure your Flask application settings: app.config['USE_X_SENDFILE'] = True Use code with caution. In your Nginx site configuration, add the internal mapping:
Never pass raw, unsanitized user inputs directly into filesystem paths. An attacker can manipulate relative paths to access sensitive system configurations. Always use send_from_directory() , or sanitize filenames using Werkzeug’s built-in utility: