Flask项目如何在浏览器展示downloads目录下文件内容?
Flask项目中展示downloads目录下文件内容的解决方案
为什么直接访问/downloads/myFile.txt会404?
Flask默认仅将static目录设置为静态资源根目录,只有该目录下的文件能通过/static/xxx的路径直接访问。你的downloads目录不在默认的静态资源路径范围内,所以直接访问会返回“Not Found”。
实现浏览器展示myFile.txt内容的两种方法
方法一:自定义路由读取文件内容返回
在app/views.py中添加以下路由代码:
from flask import current_app, render_template_string, abort import os @app.route('/downloads/myFile.txt') def show_my_file(): # 拼接文件的绝对路径 file_path = os.path.join(current_app.root_path, 'downloads', 'myFile.txt') # 检查文件是否存在 if not os.path.exists(file_path): abort(404) # 读取文件内容 with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # 用<pre>标签格式化文本内容,避免换行丢失 return render_template_string('<pre>{{ content }}</pre>', content=content)
方法二:使用Flask内置的send_from_directory函数(更规范)
同样在app/views.py中添加路由,这种方法支持匹配downloads目录下的多个文件:
from flask import current_app, send_from_directory, abort import os @app.route('/downloads/<filename>') def show_download_file(filename): downloads_dir = os.path.join(current_app.root_path, 'downloads') target_file = os.path.join(downloads_dir, filename) if not os.path.exists(target_file): abort(404) # as_attachment=False表示直接在浏览器显示内容,设为True则触发下载 return send_from_directory(downloads_dir, filename, as_attachment=False)
注意事项
- 确保
__init__.py中正确初始化了Flask app,并导入了views模块 - 如果文件是二进制类型(如图片),需要调整读取方式和返回的MIME类型
- 不建议直接将downloads目录设置为额外的静态资源路径,通过路由控制访问更安全,也便于后续添加权限校验等逻辑
内容的提问来源于stack exchange,提问作者Ira
相关产品推荐
相关产品推荐

