文件打成压缩包

发布时间 2024-01-10 13:21:36作者: 码小白很犇

将多个文件打成压缩包

引入依赖

 <!-- io常用工具类 -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.5</version>
</dependency>

自己封装成 对应的Service层,就可以了

package com.dem.ceshiDemo.controller;

import com.dem.ceshiDemo.util.StringUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author lichangben
 * @date 2021/8
 */
@Controller
public class CompressController {
    @GetMapping("/download")
    public void packagingDownload(HttpServletResponse response, String busiSn) {

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //记录 文件名存在数量
        Map<String,Integer> map = new HashMap<>();
        try{
            //遍历文件 将所有文件放入压缩包 (这里模仿多个文件进行压缩)
            for (int i = 0; i < 5; i++) {
                //原文件名称 (模仿一下 对象)
                String prefix = "dem";
                String suffix = "jpg";
                String fileName = prefix + "." + suffix;
                //判断文件名称是否存在
                if(StringUtils.isNotEmpty(StringUtils.getString(map,fileName))){
                    Integer num = map.get(fileName);
                    map.put(fileName,num+1);
                    fileName = prefix+"("+ num +")."+suffix;
                }else{
                    //不存在
                    map.put(fileName,1);
                }

                //每个文件的文件名称
                zip.putNextEntry(new ZipEntry(fileName));
                // 获取文件地址
                String fileAddress = "https://z3.ax1x.com/2021/08/18/foZvJs.jpg";

                URL url = new URL(fileAddress);
//                System.out.println(url);
                URLConnection connection = url.openConnection();
                InputStream fis = connection.getInputStream();
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                byte[] b = new byte[1024];
                int n;
                while ((n = fis.read(b)) != -1)
                {
                    bos.write(b, 0, n);
                }
                fis.close();
                bos.close();
                //生成文件内容
                IOUtils.write(bos.toByteArray(), zip);
                zip.flush();
                zip.closeEntry();
            }

            IOUtils.closeQuietly(zip);
            byte[] data = outputStream.toByteArray();
            response.reset();
            String filename = URLEncoder.encode("压缩包名称(中文需要转码,一般时间戳或者yyyyMMddhhmmss).zip", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename="+filename);
            response.addHeader("Content-Length", "" + data.length);
            response.setContentType("application/octet-stream; charset=UTF-8");
            IOUtils.write(data, response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
            /*"文件压缩失败,请确定文件存在后进行操作!"*/
            throw new RuntimeException(e.getMessage());
        }

    }

}