salem
salem

Reputation: 9

How to give exactly path in send_from_directory Flask

As we know, the" send_from_directory" need two required parameters 1- directory 2- filename

example:

app.config['UPLOAD_FOLDER'] = r"C:\Users\user\Desktop\upload_foder"

filename =" report.docx"

send_from_directory(app.config['UPLOAD_FOLDER'], filename)

My question is there any way to give the send_from_directory the exact path, for example

exact_path = r"C:\Users\user\Desktop\upload_foder\report.docx"

send_from_directory(exact_path)

Upvotes: 0

Views: 3003

Answers (2)

Sovankiry
Sovankiry

Reputation: 135

The answer is not possible because of the method flask.send_from_directory(directory, path, filename=None, **kwargs) is required two parameters one is a directory and another one is the path. In official docs from Flask suggest using send_file to Send a file from within a directory. (see more)

Now you can use the method send_file from a flask that provides the exact path with the file name. Below this the example code:

from flask import send_file
@app.route('/download')
def download():
    try:
        exact_path = r"C:\Users\user\Desktop\upload_foder\report.docx"
        return send_file(exact_path, as_attachment=True)
    except Exception as e:
        return str(e)

Upvotes: 0

Winmari Manzano
Winmari Manzano

Reputation: 482

If you want to pass the exact file path (aka return report.docx)

Use send_file(exactpath) instead of send_from_directory

Check the documentation here https://flask.palletsprojects.com/en/2.1.x/api/

Upvotes: 1

Related Questions