ajax异步下载文件
最近捯饬公司项目,需要用到ajax下载文件,所以百度了一番,综合解决方案如下:
前端html:
<span id="downloadTip"> </span>
前端ajax:
function asyncExportExcel(){
var url = "download/export";
var xhr=null;
try {
xhr=new XMLHttpRequest()
}catch(e) {
xhr=new ActiveXObject("Microsoft.XMLHTTP")
}
$("#downloadTip").html("文件下载中...");
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.responseType = "blob"; // 返回类型blob
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
// 请求完成
if (this.status === 200) {//返回200
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob); //转换为base64,可以直接放入a表情href
reader.onload = function (e) {
// 转换完成,创建一个a标签用于下载
var a = document.createElement('a');
a.download = '客户列表.xlsx';
a.href = e.target.result;
$("body").append(a); //修复firefox中无法触发click
a.click();
$(a).remove();
$("#downloadTip").html("下载完成!");
}
}};
//发送ajax请求
xhr.send();
}
后台处理:
// 导出客户报表
@RequestMapping(value = "/exportExcel")
public void exportExcel(String enterpriseIds, HttpServletResponse response) {
UserOnlineBean userOnlineBean = getUserOnlineBean();
if (null != userOnlineBean) {
try {
// 报表客户信息集开始
List<Integer> ids = SplitParmeter.splitInteger(enterpriseIds, ",");
XSSFWorkbook wb = enterpriseService.exportExcel(ids);
if (null != wb) {
String title = "客户报表";
String filename = new String(title.getBytes("gb2312"), "ISO8859-1");
response.reset();
response.setContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + filename + ".xlsx");
OutputStream out = response.getOutputStream();
wb.write(out);
out.close();
}
} catch (ServiceException e) {
} catch (Exception e) {
log.error("生成客户报表发生错误!", e);
}
}
}
作者:gzkahjl
来源:CSDN
原文:https://blog.csdn.net/gzkahjl/article/details/81408470
版权声明:本文为博主原创文章,转载请附上博文链接!