文件导出传值的get和post方式的写法(无状态化,前端vue)

通常对于excel、word类文件的导出,前端使用的是form提交数据的方式,使用的是post,还有一种方式就是url拼接参数,使用的是get方法。

get导出方式

前台使用过ajax的get方式传值,需要注意的是:该方式是将后台的数据流在前台重写了一次,所以文件名称需要在前台给定

getExcel() {
      this.$axios({
        method: "get",
        url:
          url.OBJAPIURL +
          "/exportView?start_Date=" +
          this.form.startDate +
          "&end_Date=" +
          this.form.endDate +
          "&Title=" +
          this.title +
          "&source=" +
          this.source_result,
        responseType: "blob"
      }).then(res => {
        /* let blob = new Blob([res.data], {type: "application/vnd.ms-excel;charset=utf-8"});*/
        /*  console.log(blob);
                 window.location.href = URL.createObjectURL(blob);*/
        let url = window.URL.createObjectURL(res.data);
        let link = document.createElement("a");
        if (this.form.source_result != "" && this.form.source_result != null) {
          link.download =
            "测试文件--" + this.form.source_result + ".xls";
        } else {
          link.download = "测试文件.xls";
        }
        link.href = url;
        link.click();
      });
    }

后台代码如下

@GetMapping("/exportDetail")
    public void exportDetail(HttpServletRequest request, HttpServletResponse response, @RequestParam("start_Date") String start_Date, @RequestParam("end_Date") String end_Date, @RequestParam("source") String source) throws Exception {
        
        HSSFWorkbook wbs = new HSSFWorkbook();
        //略去文件生成的逻辑代码
        try {
            //设置响应
            this.setResponseHeader(response, filename);
            OutputStream os = response.getOutputStream();
            //将文件写入流中
            wbs.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //发送响应流方法
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

post请求方式

前台代码如下

<template>
	<div class="operatingBox" style="float: right">
		<el-button type="danger" size="mini" @click="excelOut">导出</el-button>
	</div>
</template>

<script>
    //qs为vue自带组件
	import qs from 'qs';
	import url from '@/js/url';
	import utils from '@/js/utils';
	export default {
		props:['searchName'],
		data() {
			return {
				//导出
				formAct: '',//地址
				str: ''//参数
			}
		},
	methods: {
		//导出
		excelOut() {
			let formObj = {};
			formObj.pageNum = this.currentPage+"";
			formObj.pageSize = this.pagesize;
			formObj.op_start_time = this.searchName.initiateStart;
			formObj.op_end_time = this.searchName.initiateEnd;
			formObj.service_type = this.searchName.complaintValue;
			formObj.cp_start_time = this.searchName.complaintStart;
			formObj.cp_end_time = this.searchName.complaintEnd;
			formObj.deal_link = this.searchName.orderValue;
			formObj.keywords = this.searchName.searchN;
			formObj.dhv="";
			formObj.ensure_event=this.checkListVal;
			this.str = JSON.stringify(formObj);
			this.$axios.post(this.formAct, qs.stringify({str:this.str}), {
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded', //请求的数据类型为form data格式
				},
				'responseType': 'blob'  //设置响应的数据类型为一个包含二进制数据的 Blob 对象,必须设置!!!
			}).then(res => {
				let blob = new Blob([res.data], {type: "application/vnd.ms-excel;charset=utf-8"});
				/*  console.log(blob);
				window.location.href = URL.createObjectURL(blob);*/
				let url =window.URL.createObjectURL(blob);
				let link = document.createElement('a');
				link.download = '测试文件.xls';
				link.href = url;
				link.click();
			});
	  }
	},
	mounted () {
	
	}
}
</script>

后台部分代码同get方式导出类似,这里就不贴出了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js是一个流行的前端框架,可以轻松地进行数据交互和网络请求。对于导出文件post方式,主要涉及到发送POST请求和处理导出文件的响应。 首先,我们需要使用Vue的axios库或者其他网络请求库发送POST请求。可以使用axios的post方法发送POST请求,并传递相应的参数和数据。比如: ```javascript import axios from 'axios'; export default { methods: { exportData() { // 设置请求头信息 const config = { responseType: 'blob', // 指定响应的数据类型为二进制流 }; // 向服务器发送POST请求 axios.post('/export', { data: '需要导出的数据' }, config) .then(response => { // 处理导出文件的响应 this.downloadFile(response.data); }) .catch(error => { console.error(error); }); }, downloadFile(data) { // 创建一个a标签,将二进制流设置为其href属性 const blob = new Blob([data]); const url = window.URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; // 设置导出文件的名称 link.download = '导出文件名称.xlsx'; // 模拟点击a标签进行下载 link.click(); // 释放URL对象 window.URL.revokeObjectURL(url); }, }, }; ``` 上述代码中,我们使用了axios的post方法向服务器发送POST请求。在请求的配置中,通过设置responseType属性为'blob',告诉服务器返回的数据是一个二进制流。然后,在请求成功的回调函数中,调用downloadFile方法处理导出文件的响应。 downloadFile方法中,我们首先创建一个Blob对象,并将服务器返回的二进制流数据传入其中。然后,使用URL.createObjectURL方法创建一个临时URL,将a标签的href属性设置为该URL,进而生成下载链接。最后,使用模拟点击a标签的方式进行文件下载,并通过URL.revokeObjectURL方法释放URL对象。 这样,使用Vuepost方式就可以导出文件了。具体的导出文件格式和文件名称可以根据实际需求进行设置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值