How To Add Download File Feature in Flask Web Applications

Share

You can use the Content-Disposition header to force the browser to download the image instead of displaying it. Here is an example of how you can modify your route to include the Content-Disposition header:

from flask import Flask, render_template, request, send_file
app = Flask(__name__)

@app.route('/download/<path:filename>')
def download_file(filename):
    try:
        return send_file(filename, as_attachment=True, download_name=filename)
    except FileNotFoundError:
        abort(404)

In this example, when the user visits the /download/<filename> route, the server will send the file filename as an attachment with the Content-Disposition header set to attachment, which tells the browser to download the file instead of displaying it. The as_attachment=True and download_name=filename are used to set the Content-Disposition header.

Then you can use href attribute of <a> tag to point to this route and pass the filename as a parameter.

<a href="{{ url_for('download_file', filename='image.jpg') }}" class="btn btn-outline-primary">Download</a>

This way when the user clicks on download button it will directly download the image to the device download folder.

Related  How to Change Password of MySQL || How to reset MySQL Password

Note that in this example, the image file should be present in the server’s file system and the path to the file should be passed as the filename parameter to the download_file function.


If you want to download an image from an external source, you can use the requests library to fetch the image and then use the send_file function to send the image as an attachment. Here is an example of how you can do this:

import requests
import io
from flask import Flask, render_template, request, send_file

app = Flask(__name__)

@app.route('/download')
def download_file():
    image_url = request.args.get('url')
    response = requests.get(image_url)
    return send_file(
        io.BytesIO(response.content),
        download_name='image.jpg',
        as_attachment=True,
        mimetype='image/jpeg'
    )

This code uses the requests library to fetch the image from the specified URL. The send_file function is used to send the image as an attachment to the browser. The io.BytesIO(response.content) creates a binary stream of the image content, which is passed as the first argument to the send_file function. The download_name parameter is used to set the filename that will be used when the image is saved on the user’s device, and mimetype is used to specify the type of file being sent.

Related  [Free] Ai Title Generator for YouTube and Blog post

You can use query parameter in the url, like this

<a href="{{ url_for('download_file') }}?url=Your_image_URL_Here" class="btn btn-outline-primary">Download</a>

This way when the user clicks on download button it will directly download the image to the device download folder.

Please note that if the external URL requires authentication, you will need to pass the necessary credentials in the requests.get() function.


If the requests library is not available in your environment, you can use the built-in urllib library to fetch the image from an external source. Here is an example of how you can do this:

from urllib.request import urlopen
from flask import Flask, render_template, request, send_file

app = Flask(__name__)

@app.route('/download')
def download_file():
    image_url = request.args.get('url')
    image_file = urlopen(image_url)
    return send_file(
        image_file, 
        as_attachment=True, 
        download_name='image.jpg', 
        mimetype='image/jpeg'
    )

This code uses the urllib.request.urlopen() function to fetch the image from the specified URL and it will return a file-like object that can be passed to the send_file function. The download_name parameter is used to set the filename that will be used when the image is saved on the user’s device and mimetype is used to specify the type of file being sent.

Related  what is difference between request.form.get() and request.args.get()

You can use query parameter in the url, like this

<a href="{{ url_for('download_file') }}?url=URL_of_your_image_here" class="btn btn-outline-primary">Download</a>

This way when the user clicks on download button it will directly download the image to the device download folder.

Please note that if the external URL requires authentication, you will need to pass the necessary credentials in the urlopen() function.


Share

Leave a Reply

Your email address will not be published. Required fields are marked *

Top 5 Most Expensive Domains Ever Sold 4 Must-Try ChatGPT Alternatives: Perplexity AI, BardAI, Pi, and More! Types of Trading Techniques in the Stock Market. ChatGPT app now available in India this AI chatbot can help you make your life more productive. What is wrong with following function code?