SpringBoot-文件壓縮處理
前言
在工作我們經(jīng)常會(huì)出現(xiàn)有多個(gè)文件,為了節(jié)省資源會(huì)將多個(gè)文件放在一起進(jìn)行壓縮處理;為了讓大家進(jìn)一步了解我先將springboot處理的方法總結(jié)如下,有不到之處敬請(qǐng)大家批評(píng)指正!
一、文件準(zhǔn)備:
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.創(chuàng)建一個(gè)springboot web項(xiàng)目 這一步在此省略.....
2.需要的方法及類的編寫
(1)業(yè)務(wù)方法-TestService
public interface TestService { void compressFiles(List<String> fileUrls, HttpServletResponse response); }
(2)業(yè)務(wù)方法實(shí)現(xiàn)類-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.從網(wǎng)絡(luò)下載文件并寫入 ZIP try { URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); // 2.檢查響應(yīng)碼 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Failed to download file: " + fileUrl); } // 3.從 URL 中提取文件名 String pathStr = fileUrl.substring(fileUrl.lastIndexOf('/') + 1); // 4.創(chuàng)建 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.響應(yīng)信息設(shè)置處理 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 響應(yīng)對(duì)象 */ @GetMapping("/fileToZip") public void zip(@RequestParam("fileUrls") List<String> fileUrls, HttpServletResponse response) { testService.compressFiles(fileUrls, response); } }
三、方法調(diào)用展示

(1)存放到桌面

(2)解壓response.zip文件


古今成大事者,不唯有超世之才,必有堅(jiān)韌不拔之志!

浙公網(wǎng)安備 33010602011771號(hào)