最近遇到一个请求需要从数据库查询出来,然后点击下载,可以下载从数据库查询的的数据,并换行显示。
@RequestMapping("downLoadCardListByCardType")
public void downLoadCardListByCardType(String cardType, HttpServletResponse httpResponse) {
List<String> giftCodes = giftCodeManager.getCodeByCardType(cardType);
String code = "";
for (String giftCode : giftCodes) {
code += giftCode + "\n";
}
try {
byte[] bytes = code.getBytes();
httpResponse.setHeader("Content-Type", "application/force-download");
httpResponse.setHeader("Content-Disposition", "attachment; filename=\"code.txt\"");
httpResponse.getOutputStream().write(bytes);
} catch (Exception e) {
log.error("ERROR", e);
}
}
有几点需要注意:
1.方法不能带注解@ResponseBody,因为这个注解的意思是说这个方法是有返回的,如果是下载文件的话就不需要了
2.从数据库查询数据的时候尽量只查询需要的数据,因为当数据量很大时,浏览器就会响应超时