Trusted answers to developer questions

How to download files in Flask

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Downloading files from Flask applications

Flask allows downloads, just like JavaScript-based web applications do.

There are two components to this process.

HTML

There needs to be an HTML href, which will call the appropriate Python function for the download.

<a href="{{ url_for('download', filename="downloadFile.txt") }}">File</a>

Python

The Python component will consist of a function that will return the required file to the client.

@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
# Appending app path to upload folder path within app root folder
uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
# Returning file from appended path
return send_from_directory(directory=uploads, filename=filename)

This function takes the required file’s name as an argument. It then uses the os module’s path.join function to append the Flask app’s root path stored in current_app.root_path and the upload folder’s path from the root folder stored in app.config['UPLOAD_FOLDER'].

current_app is the application context. It can be used wherever an application context has been set up. app.config is a dictionary that stores a number of variables assigned by Flask itself or by the programmer. The UPLOAD_FOLDER variable has to be set up by the user.

From the appended path, the function returns the file found by send_from_directory, which takes the folder path in the first parameter and the file name in the second parameter.

Remember that you need to have access to the file you are downloading.

RELATED TAGS

python
flask
web development
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?