前端后端头传递数据

@blue.route('/download', methods=['POST'])
def download_file():
# 文件路径
data = request.get_json()
zbh = data.get('id') # 确保前端发送的 JSON 键为 'xuhao'

row = shebei.query.filter_by(id=zbh).first()

file_path = os.path.join(blue.root_path, f'../shebei/{row.zbh}/{row.zbh}.docx')

print(file_path)

# 检查文件是否存在
if os.path.exists(file_path):
# 发送文件
print("存在")
response = make_response(send_file(file_path, as_attachment=True))
response.headers['h'] = row.zbh
return response
else:
return "File not found", 404 # 返回 404 错误码表示文件未找到


row.zbh为想要传递的数据

此外还要暴露这个头才行

# 主程序的
from APP import create_app
from flask_cors import CORS


app = create_app()
CORS(app,expose_headers=["h"])

if __name__ == '__main__':
app.run(debug=True, port=5000, host='0.0.0.0')

前端接收

const	download	=	async	()	=>	{
try {
axios.post('http://127.0.0.1:5000/download', {'id':data.value}, { responseType: 'blob' })
.then(response => {
//通过头传递参数
console.log('Custom Message:', response.headers.get('h'));
const h = response.headers.get('h')
// 创建一个 URL 对象
const imageUrl = URL.createObjectURL(new Blob([response.data]));
// 创建一个 <a> 标签并设置下载属性
const link = document.createElement('a');
link.href = imageUrl;
link.download = `${h}.docx`; // 下载文件的名称
// 模拟点击下载
link.click();
// 释放 URL 对象
URL.revokeObjectURL(imageUrl);
})
.catch(() => {
const open3 = () => {
ElMessage({
message: '后台无数据',
type: 'warning',
})
}
open3()
});
} catch (error) {
// 捕获异常,显示错误消息
new proxy.$tips('服务器发生错误', 'error').mess_age();
}
};

有弊端的,我不能传递汉字,不然会出错。