Java批量下载zip
案例一
@ApiOperation(value = "根据id 批量下载文件", notes = "根据id 批量下载文件")
@RequestMapping(value = "/downloadFiles/{id}", method = RequestMethod.GET)
@ApiImplicitParam(name = "sheetId", value = "工单ID", required = true, dataType = "String", paramType = "path")
public void downloadFiles(HttpServletRequest request, HttpServletResponse response, @PathVariable String id) throws Exception {
List<OssMediaFile> list = null;
try {
EntityWrapper<OssMediaFile> wrapper = new EntityWrapper<>();
wrapper.eq("id", id);
wrapper.eq("is_delete", 0);
list = this.baseService.selectList(wrapper);
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String header = request.getHeader("User-Agent").toUpperCase();
String fileName = "附件" + String.valueOf(System.currentTimeMillis()) + ".zip";
if (!header.contains("MSIE") && !header.contains("TRIDENT") && !header.contains("EDGE")) {
fileName = new String(fileName.getBytes(), "ISO8859-1");
} else {
fileName = URLEncoder.encode(fileName, "utf-8");
fileName = fileName.replace("+", "%20");
}
response.setContentType("multipart/form-data");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
try(ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
for (int i = 0; i < list.size(); i++) {
OssMediaFile mediaFile = list.get(i);
logger.info("ossMediaFile参数:{}", JSONObject.toJSONString(mediaFile));
InputStream is = null;
try {
zipOut.putNextEntry(new ZipEntry(mediaFile.getFileName()));
String urlName = mediaFile.getFileUrl();
URL url = new URL(urlName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置是否向HttpURLConnection输出
conn.setDoOutput(false);
// 设置是否从httpUrlConnection读入
conn.setDoInput(true);
/** 设置连接方式:GET */
conn.setRequestMethod("GET");
/** 设置连接主机服务器超时时间:5000毫秒 */
conn.setConnectTimeout(5000);
/** 发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可 */
conn.connect();
int status = conn.getResponseCode();
logger.info("---status:" + status);
if(status!= HttpURLConnection.HTTP_OK){
is = conn.getErrorStream();
}else{
is = conn.getInputStream();
}
if (null == is) {
continue;
}
int temp = 0;
while ((temp = is.read()) != -1) {
zipOut.write(temp);
}
is.close();
/** 关闭远程连接 */
conn.disconnect();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
zipOut.closeEntry();
logger.info("一键下载结束");
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new RuntimeException("附件下载失败");
}
}