批量下载图片并压缩为zip 格式
@GetMapping("/downLoadImgs") public void downLoadImgs(@RequestParam(value = "ids") String ids, HttpServletResponse response) throws Exception { //1.拿到对应图片地址的url数组 String[] array = ids.split(","); //输出文件的名称 String downloadFilename = System.currentTimeMillis() + ".zip"; //转换中文否则可能会产生乱码 downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8"); // 指明response的返回对象是文件流 response.setContentType("application/octet-stream"); // 设置在下载框默认显示的文件名 response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename); ZipOutputStream zos = new ZipOutputStream(response.getOutputStream()); int i = 0; ServletOutputStream out = null; FileInputStream ips = null; for (String s : array) { //获取图片存放路径 String imgPath = filePath + File.separator + s; ips = new FileInputStream(new File(imgPath)); String type = imgPath.substring(imgPath.indexOf(".") + 1);
//获取图片名称 String name = imgPath.substring(imgPath.lastIndexOf("/") + 1); if ("png".equals(type)) { response.setContentType("image/png"); zos.putNextEntry(new ZipEntry(name)); } if ("jpeg".equals(type) || "jpg".equals(type)) { response.setContentType("image/jpeg"); zos.putNextEntry(new ZipEntry(name)); } byte[] buffer = new byte[1024]; int r = 0; while ((r = ips.read(buffer)) != -1) { zos.write(buffer, 0, r); } ips.close(); } zos.flush(); zos.close(); }
代码直接贴上
下面是使用的包引用
import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.net.URLEncoder; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;