zoukankan      html  css  js  c++  java
  • 批量下载图片并压缩为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;
  • 相关阅读:
    Matplotlib如何绘制子图
    数据挖掘的葵花宝典
    Matplotlib如何显示中文
    python绘制WordCloud词云图
    Selenium实现微博自动化运营:关注、点赞、评论
    从小白视角理解<数据挖掘十大算法>
    Laravel模型自动转换类型
    python数据分析常用图大集合
    数据分析常见概念
    Pandas数据分析基础之时间序列
  • 原文地址:https://www.cnblogs.com/huanglp/p/13531175.html
Copyright © 2011-2022 走看看