0
0
Flaskframework~30 mins

File download responses in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
File Download Responses with Flask
📖 Scenario: You are building a simple web app using Flask. The app should allow users to download a text file when they visit a specific URL.
🎯 Goal: Create a Flask app that sends a file download response with a text file named example.txt containing some content.
📋 What You'll Learn
Create a Flask app instance named app
Create a route /download that triggers the file download
Use Flask's Response object to send the file content
Set the correct headers to make the browser download the file as example.txt
💡 Why This Matters
🌍 Real World
Web apps often need to let users download files like reports, images, or documents. This project shows how to send such files correctly.
💼 Career
Backend developers frequently implement file download endpoints. Knowing how to set response headers properly is essential for user-friendly downloads.
Progress0 / 4 steps
1
Set up Flask app and file content
Import Flask and create a Flask app instance called app. Then create a variable file_content with the string value 'Hello, this is a sample file for download.'.
Flask
Need a hint?

Start by importing Flask and creating the app instance. Then assign the exact string to file_content.

2
Create download route and import Response
Import Response from flask. Then create a route /download using @app.route('/download') and define a function download_file().
Flask
Need a hint?

Remember to import Response and use the exact route and function names.

3
Create Response with file content and headers
Inside download_file(), create a Response object named response with file_content as data and mimetype='text/plain'. Then set the header Content-Disposition to 'attachment; filename=example.txt' on response.headers. Finally, return response.
Flask
Need a hint?

Use the Response constructor with the file content and set the header exactly as shown.

4
Add app run block for local testing
Add the standard Flask app run block: if __name__ == '__main__': and inside it call app.run(debug=true).
Flask
Need a hint?

This block allows you to run the Flask app locally for testing.