'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)
Solution 1:[1]
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/
Solution 2:[2]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Winmari Manzano |
| Solution 2 |
