问题遇到的现象和发生背景
vue+springboot 实现下载功能时,前端没法解析文件,但在浏览器的响应中的数据符合要求
用代码块功能插入代码,请勿粘贴截图
前端:
async downloadR(id){
request.get('search/downloadR/'+id,
{responseType: 'blob'}
).then((res)=>{
console.log('文件下载成功');
const blob = new Blob([res.data]);
const fileName = id+".R";
if ('download' in document.createElement('a')) {
//支持a标签download的浏览器
const link = document.createElement('a');//创建a标签
link.download = fileName;//a标签添加属性
link.style.display = 'none';
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
link.click();//执行下载
URL.revokeObjectURL(link.href); //释放url
document.body.removeChild(link);//释放标签
} else {
navigator.msSaveBlob(blob, fileName);
}
}).catch((res)=>{
console.log('文件下载失败');
});
},
request
const request=axios.create(
{
baseURL:'http://localhost:9090',//全局统一前缀
timeout:5000
})
//request拦截器
//可以自请求发送前对请求做一些处理
//比如统一加token,对参数统一加密
request.interceptors.request.use(config=>{
config.headers['Content-Type']='application/json;charset=utf-8'
return config;
},error => {
return Promise.reject(error);
});
运行结果及报错内容
下载后的结果
浏览器中响应 也是下载应该的结果: