vue后端返回文件流,前端实现Excel文件导出自定义文件名(新)

您所在的位置:网站首页 excel表格怎么修改文件名 vue后端返回文件流,前端实现Excel文件导出自定义文件名(新)

vue后端返回文件流,前端实现Excel文件导出自定义文件名(新)

2024-07-15 16:15| 来源: 网络整理| 查看: 265

当后端返回文件流格式前端应该如何处理? 如何将后端返回的文件流格式转换为Excel文件,并下载Excel文件? 带着这些问题看文章,希望对你有所帮助!

1. 应用场景 2. 代码块分析 3. 具体代码实现

1.应用场景

当后端返回的是文件流形式,前端应当如何处理? 如何利用blob方法将文件流转换成正常的Excel文件格式?

2.代码块分析 downloadFileExcel(res, fileName) {//自定义blob方法,导出Excel文件 let blob = new Blob([res.data]); if (!fileName) {//如果后台返回文件名称 //注意一定要和后端协调好返回的数据格式,不然会出现中文乱码问题 fileName = res.headers['content-disposition'].split('filename=').pop(); } if ('msSaveOrOpenBlob' in navigator) { window.navigator.msSaveOrOpenBlob(blob, fileName); } else { const elink = document.createElement('a'); elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); document.body.removeChild(elink); } }, 3.具体代码实现 getlist:function(){ var data={ username:_this.userName,startTime:_this.startTime,endTime:_this.endTime } _this.$axios.post(_this.httpAPI + 'slog/getExecl',data,{ headers: {'Content-Type': 'application/json','Authorization': _this.token}, responseType:"blob"//注意 需要规定后台返回文件流格式 } ).then(function(response){ if(response){ if(response.data.type==='application/json'){ //增加监听函数当接口返回错误信息或数据异常能正常捕获到 const reader=new FileReader(); reader.onload=function(){ const message=JSON.parse(reader.result); this.$message.warning(message.msg) } reader.readAsText(res.data) return false; } _this.downloadFile(response, '卷宗下载'+_this.DQTime+ '.xls');//自定义Excel文件名 }else{ _this.$message.error("服务端异常,Excel文件下载失败!"); } }); } downloadFile(res, fileName) { let blob = new Blob([res.data]); if (!fileName) { fileName = res.headers['content-disposition'].split('filename=').pop(); } if ('msSaveOrOpenBlob' in navigator) { window.navigator.msSaveOrOpenBlob(blob, fileName); } else { const elink = document.createElement('a'); elink.download = fileName; elink.style.display = 'none'; elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); URL.revokeObjectURL(elink.href); document.body.removeChild(elink); } } 写在最后

如果你觉得这篇文章写得不错或者对您有用的话请帮忙点赞加收藏,毕竟原创不易;如果您觉得文章有什么地方写得不对或者需要改进的地方,欢迎通过评论私聊博主!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3