You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask send_file未按预期路径查找文件问题求助

问题解决:Flask send_file 路径拼接错误

错误原因

你遇到的错误是因为send_file误将你传入的绝对路径当成相对路径,与Flask应用的根目录(/home/user/MAIN)进行了拼接,导致最终路径变成/home/user/MAIN/home/user/MAIN/somefile.zip,而这个路径并不存在。

解决方案

推荐使用Flask提供的send_from_directory函数来处理文件下载,它专门用于从指定目录安全发送文件,避免路径拼接问题:

from flask import Flask, send_from_directory

app = Flask(__name__)

@app.route("/download")
def download():
    # 指定文件所在的目录
    file_dir = "/home/user/MAIN"
    # 指定文件名
    filename = "somefile.zip"
    # as_attachment=True 会让浏览器触发下载动作,而不是直接打开文件
    return send_from_directory(file_dir, filename, as_attachment=True)

如果你坚持使用send_file,可以通过以下方式确保路径被正确识别为绝对路径:

import os
from flask import Flask, send_file

app = Flask(__name__)

@app.route("/download")
def download():
    file_path = "/home/user/MAIN/somefile.zip"
    # 强制转换为绝对路径,并指定root=None避免拼接
    return send_file(os.path.abspath(file_path), root=None)

额外提示

  • 使用send_from_directory更符合Flask的最佳实践,还能防止路径遍历攻击,安全性更高。
  • 确保目标文件确实存在于指定路径,并且Flask进程有读取该文件的权限。

内容的提问来源于stack exchange,提问作者11235

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 02:18:19