Ajax下载Excel文件

最近在做项目的过程中,遇到需要使用Ajax下载Excel文件的需求,以往都是通过使用form表单提交的方式来下载文件。通过一番研究,其主要实现代码如下:

1、后台接口返回二进制流

// 生成excel文件
@RequestMapping(value = “/study”, method = RequestMethod.POST)
public void study(@RequestBody ParamVO paramVO, HttpServletResponse response) throws UnsupportedEncodingException {
response.setContentType(“application/octet-stream;charset=utf-8”);
response.setContentType(“application/vnd.ms-excel”);
response.setHeader(“Content-disposition”, “attachment;filename=” + new String(paramVO.getFileName().getBytes(“utf-8”), “iso-8859-1”));
try (ByteArrayOutputStream bos = templateService.excel(paramVO);
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())) {
out.write(bos.toByteArray());
response.setHeader(“Content-Length”, String.valueOf(bos.toByteArray().length));
} catch (Exception e) {
e.printStackTrace();
}
}
2、前端页面使用Ajax下载文件

默认Ajax接收到的数据是 text 类型,现在需要将 responseType 设置为 blob 类型,来接收和处理服务器返回的二进制对象。

var xhr = new XMLHttpRequest();
xhr.open(‘post’, ‘http://localhost:8080/user/export’, true);
xhr.responseType = ‘blob’;
xhr.setRequestHeader(‘Content-Type’, ‘application/json;charset=utf-8’);
xhr.onload = function () {
if (this.status == 200) {
var blob = this.response;
var a = document.createElement(‘a’);
var url = window.URL.createObjectURL(blob);
a.href = url;
//设置文件名称
a.download = ‘用户信息.xls’;
a.click();
}
}
xhr.send(JSON.stringify({
“type” : 1,
“startDate” : “2018-01-01”,
“endDate” : “2018-12-31”
}));
}
如上所述,则是 Ajax 下载文件的大致流程和方法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值