需求内容:选择多条订单数据,将每条订单数据对应的图片下载至本地
要求:每条订单数据产生一个文件夹,并将此数据对应的图片批量下载至文件夹中,最后将所有文件夹打包zip文件下载至本地
代码实现如下:
@GetMapping("/downloadIamges")
@ApiOperation(value = "批量下载图片并生成zip文件")
@ApiImplicitParam(name = "ids", value = "以逗号隔开的字符串", dataType = "String", required = true)
public void DounloadImage(@RequestParam(value = "ids") String ids, HttpServletRequest request, HttpServletResponse response) {
//1.拿到对应图片地址List 根据实际情况修改此处
List<Map<String, Object>> list = tibaoService.getImages(ids);
//2.开始批量下载功能
try {
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
//zip文件的名称 根据实际情况修改此处
String downloadFilename = "战报合集" + sdf.format(new Date()) + ".zip";
//转换中文否则可能会产生乱码
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
//指明response的返回对象是文件流
response.setContentType("application/octet-stream");
//设置在下载框默认显示的文件名
response.setHeader("Content-Disposition", "attachment;filenamer" + downloadFilename);
ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
for (Map<String, Object> e : list) {
String[] s = e.get("fileurl").toString().split("/");
try {
URL url = new URL(e.get("fileurl").toString());
//打开连接fiLeurl
URLConnection con = url.openConnection();
//设置请求超时为5s
con.setConnectTimeout(5 * 1080);
//输出的文件流 此处设置文件夹名称 根据实际情况修改此处
File sf = new File(e.get("tibaoCode").toString() + ".-" + e.get("empMame") + "(" + e.get("empNo") + ")");
//此处设置图片名称 根据实际情况修改此处
zos.putNextEntry(new ZipEntry(sf.getPath() + "\\" + s[s.length - 1]));
InputStream fis = url.openConnection().getInputStream();
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
zos.write(buffer, 0, r);
}
fis.close();
} catch (IOException ioException) {
zos.flush();
zos.close();
}
}
} catch (Exception e) {
System.out.println(e);
}
}