我有一个flask应用,在downloads文件夹里有一个现有的xlsx文件。我试图让前端在点击按钮时下载excel文件。目前,我的flask服务器正确地访问了该文件,但在响应中却将其作为无意义的字符串数据发送。我假设我需要使用一些库将数据解析成excel工作簿,然后下载,但我很难找到答案。下面是flask的代码。
@app.route('/download')
@handle_errors
def downloadFile():
filename = request.args.get('filename')
uploadPath = sys.path[0] + '\\workflow\\downloads'
return send_file(uploadPath + '\\' + filename, as_attachment=True)
这是前端的反应代码
getFile = (e) => {
e.preventDefault();
e.persist();
const filename = e.target.getAttribute('name');
axios
.get(`http://localhost:5000/download?filename=${filename}`)
.then((data) => {
console.log('this is data: ', data);
console.log('Completed: download');
})
.catch(() => {
console.log('We were not able to complete your request.');
});
};
你的服务器似乎已经发送了一个blob。所以在前端,做。
URL.createObjectURL
并从response.data中创建url对象 href
click()
这将在客户端下载文件代码片段
getFile = (e) => {
e.preventDefault();
e.persist();
const filename = e.target.getAttribute('name');
axios
.get(`http://localhost:5000/download?filename=${filename}`)
.then((data) => {
console.log('this is data: ', data.data);
const link = document.createElement('a');
const url = URL.createObjectURL(data.data) //<---- this should be data.data
link.download = true;
link.href = url;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch(() => {
console.log('We were not able to complete your request.');
});
};