后端
from flask import Flask, send_file
app = Flask(__name__)
@app.route('/download', methods=['GET'])
def download_file():
filepath = os.path.join('static/activity/PoetryAndTheDistance/file/附件1:“智信杯”辽宁省普通高校大学生信息素养大赛活动方案.docx')
try:
return send_file(filepath, as_attachment=True)
except PermissionError:
return '文件权限错误,无法访问', 403
except Exception as e:
return f'发生错误:{str(e)}', 500
if __name__ == '__main__':
app.run()
file_path
变量中提供要下载的文件的路径。- 当访问
download
路由时,会触发download_file
函数,该函数使用send_file
方法将文件发送到客户端以进行下载 as_attachment=True
表示将文件作为附件下载,而不是在浏览器中直接打开。
前端
<button id="download-btn">点击下载文件</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('#download-btn').click(function() {
window.location.href = '/download';
});
});
</script>