• 批量下载图片并压缩为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;
  • 相关阅读:
    2.5.1 选择器中含有特殊符号的注意事项
    动手为王:由一条UPDATE语句引发的一波三折深入实践(含PPT)
    基于JSR-356实现的Tyrus WebSocket框架的消息传递机制初步了解
    基于JSR-356实现的Tyrus WebSocket框架的消息传递机制初步了解
    Pre-shared key
    Pre-shared key
    Pre-shared key
    Pre-shared key
    confluence+jira
    confluence+jira
  • 原文地址:https://www.cnblogs.com/huanglp/p/13531175.html
Copyright © 2020-2023  润新知