Java批量导出图片,并压缩成zip
@Override public void exportQrCode(YardPcPageParam param, HttpServletResponse response) { QueryWrapper<YardEntity> queryWrapper = this.toPcListQuery(param); List<YardEntity> yardEntityList = this.list(queryWrapper); if (yardEntityList.size() == 0) { throw new BizException("暂无数据!"); } List<YardSimpleVo> yardSimpleVos = yardEntityList.stream().map(e -> { YardSimpleVo vo = new YardSimpleVo(); vo.setName(e.getGroupId() + "大组" + e.getHouseNumber()); vo.setUrl(StringUtils.isEmpty(e.getQrCode()) ? "" : OssUtils.getUrlByOss(e.getQrCode())); return vo; }).collect(Collectors.toList()); String zipFileName = "yardsQrCode.zip"; //响应头的设置 response.reset(); response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName); ZipOutputStream zipOutputStream = null; try { zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream())); zipOutputStream.setMethod(ZipOutputStream.DEFLATED); //设置压缩方法 } catch (Exception e) { e.printStackTrace(); } DataOutputStream os = null; for (YardSimpleVo yardSimpleVo : yardSimpleVos) { if (StringUtils.isEmpty(yardSimpleVo.getUrl())) { continue; } String fileName = yardSimpleVo.getName() + ".jpg"; File file = new File(""); try { URL url = new URL(yardSimpleVo.getUrl()); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); InputStream is = conn.getInputStream(); file = FileUtils.inputStreamToFile(is, fileName); } catch (Exception e) { e.printStackTrace(); } if (file.exists()) { try { assert zipOutputStream != null; zipOutputStream.putNextEntry(new ZipEntry(fileName)); os = new DataOutputStream(zipOutputStream); InputStream is = new FileInputStream(file); byte[] b = new byte[100]; int length = 0; while ((length = is.read(b)) != -1) { os.write(b, 0, length); } is.close(); zipOutputStream.closeEntry(); } catch (IOException e) { e.printStackTrace(); } } } try { if (os != null) { os.flush(); os.close(); } if (zipOutputStream != null) { zipOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } }
需求:批量下载图片,并打包成zip导出