Home > Mobile >  How to give exactly path in send_from_directory Flask
How to give exactly path in send_from_directory Flask

Time:04-26

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)

CodePudding user response:

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/

CodePudding user response:

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)

CodePudding user response:

See os.path documentation

>>> import os
>>> os.path.abspath("upload_foder\report.docx")
'C:\Users\user\Desktop\upload_foder\report.docx'

Note that upload_foder/report.docx must exist under os.getcwd().

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:\Users\user\Desktop\upload_foder\report.docx")
'C:\Users\user\Desktop\upload_foder\report.docx'

Use os.path.join() for the proper path component separators for different OSes.

  • Related