环境:前后端完全分离,后端flask_restful,前端vue
from flask_restful import reqparse, Resource from flask import send_from_directory,send_file,safe_join from werkzeug.utils import secure_filename class DownloadTemplates(Resource): def get(self): parser = reqparse.RequestParser(trim=True) parser.add_argument('filename', required=True, nullable=False, location=['args']) args = parser.parse_args() filename = args['filename'] path = handle_manage.template_dir response = send_from_directory(path, filename, as_attachment=True) return response 注意:这种做法有时会报错404,提示找不到url genericpath.py 如果系统安装了这个组件的话: 会替换系统自带的path功能,导致,path失效了。最终会找不到文件。 代码只有这样简短的几句话而已。就是这个os.path.isfile会有问题。所以,放在uploaded_file中来完成这个动作,就可以了 class DownloadTemplates(Resource): def get(self): parser = reqparse.RequestParser(trim=True) parser.add_argument('filename', required=True, nullable=False, location=['args']) args = parser.parse_args() UPLOAD_FOLDERS = handle_manage.template_dir filename = args['filename'] return send_file(safe_join(UPLOAD_FOLDERS, secure_filename(filename)), as_attachment=True)
前端
this.currentNode.path 为文件绝对路径
//方法一
//response.data + '/' + download_url 是绝对地址
window.open(response.data + '/' + download_url, '_blank');
//方法二
let a = document.createElement('a')
a.href = response.data + '/' + download_url
a.click();