springboot將檔案處理成壓縮檔案

[奋斗]發表於2024-11-13

前言

在工作我們經常會出現有多個檔案,為了節省資源會將多個檔案放在一起進行壓縮處理;為了讓大家進一步瞭解我先將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檔案

相關文章