前段,js 下载
1,采用ajax异步调用,后台生成文件,返回前段,文件的名称
2,文件名称采用唯一的UUID生成
function ajaxExport(){
var name = $('#name').val();
if(name == undefined ){
name = "";
}
$.post("${ctx}/xzcf/todo/ajaxExport",parameters,function(data){
top.layer.closeAll('loading');
if(data.ok){
top.layer.confirm('文件导出成功,是否下载?', {
btn: ['下载','取消']
},function(){
location.href="${ctx}/xzcf/todo/download?fileId="+data.fileId+"&ext="+data.ext;
top.layer.closeAll();
});
}else{
errorx("文件导出失败!")
}
},"json");
}
后端处理
@ResponseBody
@RequestMapping(value = "ajaxExport")
public Map<String, Object> exportFile( @RequestParam Map<String, Object> parameters, HttpServletRequest request, HttpServletResponse response,
RedirectAttributes redirectAttributes) {
boolean ok = false;
String fileId = IdGen.uuid();
String ext = null;
// 获取有效数据
List<MapEntity> datas = xzcfToDoService.findFeedList(parameters);
try {
// 生成对应的excel文件
File file = xzcfToDoService.createPushExcel(datas, fileId);
if (file != null) {
ok = true;
ext = Files.getFileExtension(file.getName());
}
} catch (IOException e) {}
// 返回ajax 数据
Map<String, Object> result = Maps.newHashMap();
result.put("ok", ok);
result.put("fileId", fileId);
result.put("ext", ext);
return result;
}
@Transactional(readOnly = false)
public File createPushExcel(List<MapEntity> entities,String fileId) throws IOException {
// 1. 生成一个file 文件
File resultFile = null;
try {
if(StringUtils.isBlank(fileId)){
fileId = IdGen.uuid();
}
String[] headers = {"主体名称"};
String[] keys = {"cfxdrmc"};
ExportExcel ex =new ExportExcel("行政处罚反馈数据", headers).setDataList1(entities, keys);
String tmpPath = DataUtils.getServletContextRealPathResolver().get(Global.getConfig("tmpPath"));
File dir = new File(tmpPath);
if (!dir.exists()) {
dir.mkdirs();
}
resultFile = new File(tmpPath + "/" + fileId + ".xls");
FileOutputStream os = new FileOutputStream(resultFile);
ex.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
return resultFile;
}
下载代码,
URLEncoder.encode 编码,防止,下载中文乱码
@RequestMapping("download")
public String download(String fileId, String ext, HttpServletRequest request, HttpServletResponse response) {
try {
response.reset();
response.setContentType("application/octet-stream");
String fileName = URLEncoder.encode(xzcfName+"."+ext, "utf-8");
String tmpPath = DataUtils.getServletContextRealPathResolver().get(Global.getConfig("tmpPath"));
File file = new File(tmpPath + "/" + fileId + "." + ext);
System.out.println(file.exists());
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
response.addHeader("Content-Disposition", "attachment; filename=\""+ fileName +"\"");
IOUtils.copy(is, os);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}