导出excel文件或者下载文件采用blob文件流的形式

飞一样的编程
飞一样的编程
擅长邻域:Java,MySQL,Linux,nginx,springboot,mongodb,微信小程序,vue

分类: springboot vue 专栏: vue学习 springboot学习 标签: 导出文件

2024-07-06 10:23:39 230浏览

导出excel文件或者下载文件采用blob文件流的形式

采用这种方式的话,就不需要把文件保存到服务器了

前端vue

    <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportStudentInfo"
          >学员导出</el-button>

          
  exportStudentInfo(){
      exportStudent(this.forms).then(resp=>{
        this.fileDownload(resp.data, "学生信息.xlsx");
      })
    },
export function exportStudent() {
    return request({
        url: "/student/info/excel/exportStudent",
        responseType:'blob',
        method:'get',
    })
}
export function fileDownload(data, filename, mime, bom) {
	const blobData = (typeof bom !== 'undefined') ? [bom, data] : [data];
	const blob = new Blob(blobData, {type: mime || 'application/octet-stream'});
	if (typeof window.navigator.msSaveBlob !== 'undefined') {
		// IE workaround for "HTML7007: One or more blob URLs were
		// revoked by closing the blob for which they were created.
		// These URLs will no longer resolve as the data backing
		// the URL has been freed."
		window.navigator.msSaveBlob(blob, filename);
	}
	else {
		const blobURL = (window.URL && window.URL.createObjectURL) ? window.URL.createObjectURL(blob) : window.webkitURL.createObjectURL(blob);
		const tempLink = document.createElement('a');
		tempLink.style.display = 'none';
		tempLink.href = blobURL;
		tempLink.setAttribute('download', filename);

		// Safari thinks _blank anchor are pop ups. We only want to set _blank
		// target if the browser does not support the HTML5 download attribute.
		// This allows you to download files in desktop safari if pop up blocking
		// is enabled.
		if (typeof tempLink.download === 'undefined') {
			tempLink.setAttribute('target', '_blank');
		}

		document.body.appendChild(tempLink);
		tempLink.click();

		// Fixes "webkit blob resource error 1"
		setTimeout(function() {
			document.body.removeChild(tempLink);
			window.URL.revokeObjectURL(blobURL);
		}, 200)
	}
}

后端接口

    @ApiOperation("导出学生信息")
    @GetMapping("/excel/exportStudent")
    public void importStudent(HttpServletResponse response, StudentInfo studentInfo) throws IOException {
        //查询学生信息
        List<StudentInfoExcel> studentInfoExcels = studentInfoService.studentByTenantIdExportList(studentInfo);
        EasyExcel.write(response.getOutputStream(), StudentInfoExcel.class).sheet("学生信息").doWrite(studentInfoExcels);
    }

前端响应拦截器

这个其实不是重点,那为啥删掉这段代码会报错?

这是因为不加这个的话,由于咱们后端返回的因为没走统一返回结果,所以压根没code,那么响应拦截器里如果不加上述代码的话会导致进到code!=200里

所以就会报错

Notification.error({
        title: res.data.message
      })
      return Promise.reject('error')

而加上上面的那个处理的话,就会正常进入接口的回调响应

blob格式的文件流

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695