ajax response 导出文件

来源:互联网 发布:js cookie 跨域 编辑:程序博客网 时间:2024/06/01 10:16

前段
form隐藏域
<form id="form" style="display: none">
</form>
$.ajax({
url: createTxt/Excel, -- 在服务端生成文件
type:"POST",
async: false,
data:{data:queryData},
success: function (text) {
mini.unmask();
var result=mini.decode(text);
if(result.data.code =='0'){
expAjax(result.data.filePath,result.data.fileName);
}else{
mini.alert("导出出现异常");
return false;
}
},error:function(e){
mini.unmask();
mini.alert("导出出现异常。");
}
});
function expAjax(pathWj, wjmc) {
var param = '?pathWj=' + pathWj + '&wjmc=' + wjmc;
var form = $("#form"); //form表单
form.attr('target', '');
form.attr('method', 'post');
form.attr('action', downTxt/Excel + param);
form.submit(); //表单提交
}

@RequestMapping(value = "/downTxt/Excel ", method = RequestMethod.POST)
@ResponseBody
public ResultDTO downTxt/Excel (HttpServletRequest request,
HttpServletResponse response) {
ResultDTO dao = new ResultDTO();
try {
String pathWj = request.getParameter("pathWj");
String wjmc = request.getParameter("wjmc");
byte[] b1 = readFileByBytes(pathWj);
response.addHeader("Content-Disposition",
"attachment;filename=" + wjmc + ".xls");  --这里的文件名称要和生成的文件名称保持一致,不然下载不成功
response.setContentType("application/x-download");
response.getOutputStream().write(b1);
File file = new File(pathWj );
file.delete();
dao.setMessage("文件导出成功。");
} catch (Exception e) {
LOG.info("mesg", e);
dao.setMessage("导出失败。");
}

return dao;
}

public byte[] readFileByBytes(String fileName) {
InputStream in = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
in = new FileInputStream(fileName);
byte[] buf = new byte[1024];
int length = 0;
while ((length = in.read(buf)) != -1) {
out.write(buf, 0, length);
}
} catch (Exception e1) {
LOG.error("导出异常:" + e1.getMessage(), e1);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
LOG.error(e1.getMessage(), e1);
}
}
}
return out.toByteArray();
}


原创粉丝点击