尝试了下$.ajax或者$.post等方式去后台获取文件流到response推到前台时总是失败的。
想到了另外一种方式,采用隐藏form提交的方式,再用response来推就可以。
js:
function export1() {
var form = $("<form>");
form.attr('style','display:none');
form.attr('target','');
form.attr('method','post');
form.attr('action','${pageContext.request.contextPath}/edocinfo/export');
var input1 = $('<input>');
input1.attr('type','hidden');
input1.attr('name','item');
input1.attr('value',JSON.stringify($.serializeObject($('#searchForm'))));
$('body').append(form);
form.append(input1);
form.submit();
form.remove();
}
然后后台采用老办法,往response里写文件流,往前台推。
我附带贴上代码:
@RequestMapping("/export")
@ResponseBody
public void exportXLS(@RequestParam("item")String item,HttpServletResponse response) {
try {
String workbookName = "单证宝无纸化电子提单数据统计"
+ DateUtil.formatDate(new Date(),"yyyyMMdd") + ".xls";
//专治中文乱码
String fileName = new String(workbookName.getBytes("gb2312"),"ISO8859-1" );
item = item.replace(""","\"");
logger.info(item);
//查询条件封装
Edocinfo info = JSON.parSEObject(item,Edocinfo.class);
//封装excel byte[] data = edocinfoService.exportXLS(info); // 放到response中推到前台 response.setContentType("application/x-download"); response.addHeader("Content-Disposition","attachment;filename=" + fileName); ServletOutputStream out = response.getOutputStream(); InputStream fileStream = new ByteArrayInputStream(data); IoUtils.copy(fileStream,out); out.flush(); out.close(); }catch(Exception e){ e.printStackTrace(); } }
原文链接:https://www.f2er.com/ajax/164474.html