该案例从数据库查询出来数据,然后打包下载
@RequestMapping("/download")
public void download(UCFQRCodeRequestBO qrCodeRequestBO, HttpSession session, HttpServletResponse response) {
LOGGER.info("二维码下载,入参:" + JSON.toJSONString(qrCodeRequestBO));
ZipOutputStream zos = null;
try {
List<UCFQRCodeResponseBO> list = null;
if ("this".equals(qrCodeRequestBO.getBatchNo())) {
list = (List<UCFQRCodeResponseBO>) session.getAttribute(SUCCESS_DATA_SESSION);
} else {
FsResultBO<List<UCFQRCodeResponseBO>> fsResultBO = qrCodeService.searchQRCodeList(qrCodeRequestBO);
if (fsResultBO.isSuccess()) {
list = fsResultBO.getRespBO();
} else {
LOGGER.info("查询二维码信息列表失败!" + fsResultBO.getRespMsg());
}
}
LOGGER.info("下载数据信息:" + JSON.toJSON(list));
if (list != null && list.size() > 0 && list.size() <= 200) {
// 设置浏览器显示的内容类型为Zip
response.setContentType("application/zip");
// 设置内容作为附件下载,并且名字为:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = sdf.format(new Date()) + ".zip";
response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("GBK"), "ISO8859-1"));
// 装饰输出流为Zip输出流
zos = new ZipOutputStream(response.getOutputStream());
// 读取文件的缓存
for (UCFQRCodeResponseBO responseBO : list) {
String filePath = responseBO.getFilePath();
if (fileClient.existFile(filePath)) {
InputStream inputStream = fileClient.downloadFile(filePath);
// 把inputstream写入到zip流里
writeToZipFile(zos, inputStream, filePath);
} else {
LOGGER.info("二维码图片不存在!" + filePath);
}
}
}
session.removeAttribute(SUCCESS_DATA_SESSION);
} catch (Exception e) {
LOGGER.error("查询二维码信息列表异常!", e);
} finally {
if (zos != null) {
try {
zos.close(); // 最后要关闭流,否则使用RAR打开会提示“不可预料的压缩文件末端”
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @Description: 把多个输入流的内容写到输出流里
* @param zipOutput
* @param inputStream
* @param fileName
*/
private void writeToZipFile(ZipOutputStream zipOutput, InputStream inputStream, String fileName)
throws IOException {
BufferedInputStream bis = null;
try {
if (fileName.contains("/")) {
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
}
bis = new BufferedInputStream(inputStream);
ZipEntry entry = new ZipEntry(fileName);
zipOutput.putNextEntry(entry);
// 向压缩文件中输出数据
int length;
byte[] buffer = new byte[4096];
while ((length = bis.read(buffer)) != -1) {
zipOutput.write(buffer, 0, length);
}
} catch (IOException e) {
LOGGER.error("将图片文件写入压缩文件中出现异常:", e);
} finally {
if (zipOutput != null) {
zipOutput.flush();
zipOutput.closeEntry();
}
if (bis != null) {
bis.close();
}
}
}
参考:http://www.cnblogs.com/yzuzhang/p/4763606.html 里面还有另一种文件下载方式