简体   繁体   English

如何在 send_from_directory Flask 中给出准确的路径

[英]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我们知道,“send_from_directory”需要两个必填参数1-目录2-文件名

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我的问题是有什么办法可以给 send_from_directory 确切的路径,例如

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)如果你想传递确切的文件路径(又名 return report.docx)

Use send_file(exactpath) instead of send_from_directory使用 send_file(exactpath) 而不是 send_from_directory

Check the documentation here https://flask.palletsprojects.com/en/2.1.x/api/在此处查看文档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.答案是不可能的,因为方法flask.send_from_directory(directory, path, filename=None, **kwargs)需要两个参数,一个是目录,另一个是路径。 In official docs from Flask suggest using send_file to Send a file from within a directory.在 Flask 的官方文档中,建议使用send_file从目录中发送文件。 ( see more ) 查看更多

Now you can use the method send_file from a flask that provides the exact path with the file name.现在您可以使用 flask 中的send_file方法,该方法提供带有文件名的确切路径。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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