Flask中使用send_file实现文件下载报错求助
Flask文件下载功能故障修复方案
问题概述
开发Flask应用时,用户无法下载与主程序同目录的CSV文件以及static目录下的图片,功能失效,以下是相关代码、目录结构及报错信息。
原代码展示
Python代码
app = Flask(__name__) @app.route('/', methods= ['POST', 'GET']) def result(): if request.method == 'GET': return render_template('result.html') elif request.method == 'POST': if request.form['submit_button'] == 'Download CSV': return send_file('name.csv', as_attachment=True, download_name='name.csv') elif request.form['submit_button'] == 'Download plot': return Flask.send_static_file('static/plot.png', as_attachment=True, download_name='plot.png') if __name__ == '__main__': app.run(debug = True, host='0.0.0.0')
HTML代码
<div class = 'wrap'> <form method="POST"> <input type="submit" name="submit_button" value="Download CSV"> <input type="submit" name="submit_button" value="Download plot"> </form> </div>
目录结构

报错信息

故障原因与修复方案
1. 缺失必要导入语句
原代码未导入request、send_file等核心模块,直接运行会触发NameError。需在代码开头补充:
from flask import Flask, render_template, request, send_file import os
2. CSV文件路径不可靠
直接使用相对路径'name.csv'可能因运行时工作目录不一致导致文件找不到,改用应用根目录拼接绝对路径:
csv_path = os.path.join(app.root_path, 'name.csv') return send_file(csv_path, as_attachment=True, download_name='name.csv')
3. 静态文件下载方法错误
Flask.send_static_file调用方式错误,且参数不应包含static/前缀(send_static_file默认从static目录查找)。推荐用send_file配合绝对路径读取图片,更直观可靠:
plot_path = os.path.join(app.root_path, 'static', 'plot.png') return send_file(plot_path, as_attachment=True, download_name='plot.png')
修复后的完整Python代码
from flask import Flask, render_template, request, send_file import os app = Flask(__name__) @app.route('/', methods= ['POST', 'GET']) def result(): if request.method == 'GET': return render_template('result.html') elif request.method == 'POST': if request.form['submit_button'] == 'Download CSV': csv_path = os.path.join(app.root_path, 'name.csv') return send_file(csv_path, as_attachment=True, download_name='name.csv') elif request.form['submit_button'] == 'Download plot': plot_path = os.path.join(app.root_path, 'static', 'plot.png') return send_file(plot_path, as_attachment=True, download_name='plot.png') if __name__ == '__main__': app.run(debug = True, host='0.0.0.0')
内容的提问来源于stack exchange,提问作者Juan Ignacio Ochotorena
相关产品推荐
相关产品推荐

