简体   繁体   中英

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)

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/

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM