业务需求:由于和银行合作,要做个离线版的应用,而每天把请求的报文和mq保存成文件的形式,然后我们拿到文件进行后续的报文读入,走后续流程。现需求是用定时器job每天把前一天状态发生改变的单子的回参报文和生产的mq都导出来供后续银行读取信息进行后续操作。我的部分就是把文件进行列表,点击能下载出来对应时间的文件。
说白了比较简单。但是过程还是摸索着来。因为涉及前后台。前台怎样传值,后台怎样返回才能让文件在页面实现下载?这里参考贴:Java文件下载的几种方式
框架:SSM+easyui
总结:文件下载需要页面选中对应的文件列表。然后传相关参数到后台,但是我尝试用ajax的post请求:
$.post({
url:basePaht+'controller层路径'
date:{“id”:id,‘filePath’:filePath},
type:"post",
dataType:"json"
})
发现传参没问题,比较方便,但是后台Controller对应的方法是这样的,每次执行结束后发现前台页面报错。就是这个ajax报的。Controller层方法框架大致如下:
@RequestMapping("/downLoadXml")
public void downloadXmlFile(HttpServletRequest request,HttpServletResponse response){
//处理过程省略先
}
因为后台是void的,并没有往前台返回。所以这个ajax就报错。后来把ajax换成链接形式到后台就可以了:
window.location.href=“对用controller层方法的url”+参数;
参数添加为key=value形式后缀到url。
前后台配合的结论是:前台为超链接+后台response写入文件流。
@RequestMapping("/downLoadXml")
public void downloadXmlFile(HttpServletRequest request,HttpServletResponse response){
String id=request.getParameter("id");
String filePath=request.getParameter("filePath");
try{
filePath=URLDecoder.decode(filePath,"utf-8");
}catch(UnsupporedEncodingException e){
logger.error("filePath转码出错",e);
}
Dto dto=new BaseDto();
dto.put("id",id);
dto.put("filePath",filePath);
//更新下载次数
String updateTimes=orderExportAction.updateTimes(dto);
try {
// path是指欲下载的文件的路径。
File file = new File(filePath);
// 取得文件名。
String fileName = file.getName();
// 取得文件的后缀名。
//String ext = filename.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}