后端返回的内容
传参后拿到的是上图显示的结果,前端如何实现下载此文件为excle或者zip呢?一起来看看吧:
前端实现下载
-
在项目封装的统一请求的文件中加入
responseType : "blob"
即可。注意:该代码应与
headers
并列而不是包含,我在项目中不小心写入headers
中,结果一直是乱码,耗时较长。以下是我加入responseType : "blob"
的地方,根据自己项目封装的请求方法加入即可。 -
点击下载按钮时加入以下代码
//按钮 <el-button type="primary" @click="downLoadInventory">下载</el-button> //下载方法 downLoadInventory(){ this.$http.inventoryTask.exportByTask(param).then((res) => { //调接口传参 //下载zip // 参数1:接口返回数据;参数2:blob文件类型;参数3:文件名称 downLoadFile(res,'application/zip',"文件名" + '.zip'); //downLoadFile方法在下面 //下载excel //downLoadFile(res,'application/vnd.ms-excel',"文件名"); } } //downLoadFile() downLoadFile(data,type,fileName) { const element= document.createElement('element'); const blob = new Blob([data], { type: type }) element.style.display = 'none'; element.href = window.URL.createObjectURL(blob); //可以打印看看blob element.download = fileName; //下载的文件名 document.body.appendChild(element); element.click(); window.URL.revokeObjectURL(element); //释放 }
这样就可以下载啦,有问题在评论区欢迎指出哦~ ❤️