ajax方式下载文件附带loading效果
<button type="button" class="btn btn-primary" οnclick="doexportexcleAjax()">ajax导出</button>
function doexportexcleAjax() {
jQuery('#mainList').showLoading();
var url = '${ctx}/bus/bianzhi/export/exportAjax';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true); // 也可以使用POST方式,根据接口
xhr.responseType = "blob"; // 返回类型blob
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {
jQuery('#mainList').hideLoading();
// 请求完成
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 = '编制信息.xls';
a.href = e.target.result;
$("body").append(a); // 修复firefox中无法触发click
a.click();
$(a).remove();
}
}
};
// 发送ajax请求
xhr.send()
}
/**
* Ajax导出编制基本信息
*/
@RequestMapping("exportAjax")
public void exportAjax(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) {
biazhiExportService.exportBianzhiHardlistsAjax(request, response);
}
/**
* 导出编制基本信息
*
* @param request
*
* @param response
* @param busPeopleBasePO
*/
public void exportBianzhiHardlistsAjax(HttpServletRequest request, HttpServletResponse response) {
List<BusBianzhiDTO> findList = bianzhiDTODao.findList(new BusBianzhiDTO());
if (!findList.isEmpty()) {
String rootPaths = this.getClass().getResource("/").getPath().replaceFirst("/WEB-INF/classes/", "/static/");
rootPaths = rootPaths.substring(1, rootPaths.length());// 根路径
String exclePath = rootPaths + "textExcle" + IdGen.uuid() + "/";
String downPath = "";
String downName = "";
Map<String, Object> map = new HashMap<>();
File src = new File(exclePath);
if (!src.exists()) {// doc所在文件夹不存在
src.mkdirs();// 创建文件夹
}
downName = "编制信息.xls";
downPath = exclePath + downName;
map.put("downName", downName);
map.put("downPath", downPath);
map.put("bianzhiList", findList);
FreemarkerWord.exportBianzhiExcel(map, "bianzhidaochumuban");
File f = new File(downPath);
FileInputStream inputStream = null;
OutputStream outPutStream = null;
try {
response.setContentType("application/ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + new String(downName.getBytes("utf-8"), "ISO8859-1"));
inputStream = new FileInputStream(f);
outPutStream = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
outPutStream.write(b, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 这里主要关闭。
try {
outPutStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
deleteDir(exclePath);
}
} else {
// 导出空的模板
String appBasePath = request.getSession().getServletContext().getRealPath("/");
String url = appBasePath + "/template/编制信息模板.xlsx";
downTpl(url, response);
}
}