原理:设置response对象的header以及contentType并获取outputStream,往流中写入数据即可。
eg:
@RequestMapping(value = "/license/download/{companykey}", method = RequestMethod.GET)
public String licenseDownload(@PathVariable("companykey") String companykey,HttpServletResponse response){
OutputStream toClient = null;
// 获取数据
String license = licenseService.jointLicense(companykey);
if (license.equals("-1")){
return "该license不存在!";
} else if (license.equals("-2")) {
return "该license已过期!";
}
try {
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=license");
response.addHeader("Content-Length", "" + license.getBytes().length);
toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(license.getBytes());
toClient.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
return "1";
}
主要业务情景是:通过条件,从数据库查询结果,并以文件的形势让用户下载。
在实现这个业务的时候,碰到了一个小问题,就是网上查询的时候,有博客是直接return response对象。但是由于我需要通过验证返回不同的结果。如果return response对象就不能返回数据,后面发现,在返回结果的时候,response对象自动就返回了,所以不用画蛇添足。