springboot将文件处理成压缩文件

前言

在工作我们经常会出现有多个文件,为了节省资源会将多个文件放在一起进行压缩处理;为了让大家进一步了解我先将springboot处理的方法总结如下,有不到之处敬请大家批评指正!

一、文件准备:

复制代码
https://qnsc.oss-cn-beijing.aliyuncs.com/crmebimage/public/product/2024/11/12/be353210028a3da732c8ba34073fb4ca.jpeg
https://qnsc.oss-cn-beijing.aliyuncs.com/crmebimage/public/product/2024/11/13/5bbf579109db2641249deab4be4340f6.jpeg
https://qnsc.oss-cn-beijing.aliyuncs.com/crmebimage/public/product/2024/11/13/1808773678128361474.xlsx

二、处理步骤:

1.创建一个springboot web项目 这一步在此省略.....

2.需要的方法及类的编写

(1)业务方法-TestService
复制代码
public interface TestService {
    void compressFiles(List<String> fileUrls, HttpServletResponse response);
}
(2)业务方法实现类-TestServiceImpl
复制代码
@Service
@Slf4j
public class TestServiceImpl implements TestService {

    @Override
    public void compressFiles(List<String> fileUrls, HttpServletResponse response) {
        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (String fileUrl : fileUrls) {
                // 1.从网络下载文件并写入 ZIP
                try {
                    URL url = new URL(fileUrl);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    // 2.检查响应码
                    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                        throw new IOException("Failed to download file: " + fileUrl);
                    }
                    // 3.从 URL 中提取文件名
                    String pathStr = fileUrl.substring(fileUrl.lastIndexOf('/') + 1);
                    // 4.创建 ZIP 条目
                    ZipEntry zipEntry = new ZipEntry(pathStr);
                    zipOut.putNextEntry(zipEntry);
                    // 5.读取文件的输入流
                    try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) {
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = inputStream.read(buffer)) >= 0) {
                            zipOut.write(buffer, 0, length);
                        }
                    }
                    zipOut.closeEntry();
                } catch (IOException e) {
                    log.error("Error processing file URL: " + fileUrl, e);
                    throw new RuntimeException(e);
                }
            }
       // 6.响应信息设置处理
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=test.zip");
            response.flushBuffer();
        } catch (IOException e) {
            log.error("Error compressing files", e);
            throw new RuntimeException(e);
        }
    }
}
(3)控制器类的编写-TestController
复制代码
/**
 * @Project:
 * @Description:
 * @author: songwp
 * @Date: 2024/11/13 14:50
 **/
@RequestMapping("test")
@RestController
@Slf4j
public class TestController {

    @Autowired
    private TestService testService;

    /**
     * 文件压缩
     *
     * @param fileUrls 要压缩的文件 URL 列表
     * @param response 响应对象
     */
    @GetMapping("/fileToZip")
    public void zip(@RequestParam("fileUrls") List<String> fileUrls, HttpServletResponse response) {
        testService.compressFiles(fileUrls, response);
    }
}

三、方法调用展示

(1)存放到桌面

(2)解压response.zip文件

相关推荐
双叶83614 小时前
(C++)STL标准库(vector动态数组)(list列表)(set集合)(map键值对)相关对比,基础教程
c语言·开发语言·数据结构·c++·list
sniper_fandc2 天前
Redis数据类型之list
数据库·redis·list
素雪风华2 天前
Jenkins+Gitee+Docker容器化部署
java·docker·gitee·jenkins·springboot·持续部署
404未精通的狗2 天前
(C++)STL:list认识与使用全解析
开发语言·c++·list
写不出来就跑路2 天前
WebClient与HTTPInterface远程调用对比
java·开发语言·后端·spring·springboot
乌萨奇也要立志学C++4 天前
【C++详解】STL-list模拟实现(深度剖析list迭代器,类模板未实例化取嵌套类型问题)
c++·list
秋说4 天前
【PTA数据结构 | C语言版】在顺序表 list 的第 i 个位置上插入元素 x
c语言·数据结构·list
写不出来就跑路4 天前
SpringBoot静态资源与缓存配置全解析
java·开发语言·spring boot·spring·springboot
秋说4 天前
【PTA数据结构 | C语言版】返回单链表 list 中第 i 个元素值
c语言·数据结构·list
双叶8365 天前
(C++)任务管理系统(正式版)(迭代器)(list列表基础教程)(STL基础知识)
c语言·开发语言·数据结构·c++·list