Spring Boot如何实现不落地存储直接读取上传的zip压缩包内容
内存处理ZIP上传的实现方案
不用将上传的压缩包落盘,直接读取MultipartFile的输入流即可完成全部解压读取操作,优化后的代码如下:
优化后完整代码
import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.nio.charset.StandardCharsets; @RequestMapping(value ="/upload", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) throws IOException { System.out.println(file.getOriginalFilename()); List<String> contentList = new ArrayList<>(); byte[] buffer = new byte[1024]; // 直接用上传文件的输入流构造ZipInputStream,不需要落盘 try (InputStream inputStream = file.getInputStream(); ZipInputStream zis = new ZipInputStream(inputStream, StandardCharsets.UTF_8)) { ZipEntry zipEntry; while ((zipEntry = zis.getNextEntry()) != null) { // 跳过目录,只处理文件 if (zipEntry.isDirectory()) { continue; } // 读取当前压缩文件的全部内容 ByteArrayOutputStream baos = new ByteArrayOutputStream(); int read; while ((read = zis.read(buffer, 0, 1024)) >= 0) { baos.write(buffer, 0, read); } // 转成字符串加入列表,可根据实际xml编码调整字符集 contentList.add(baos.toString(StandardCharsets.UTF_8)); zis.closeEntry(); } } System.out.println("Unzip complete"); System.out.println("--------------------------------"); System.out.println("List:"+ contentList); return new ResponseEntity<>(contentList, HttpStatus.OK); }
核心改动说明
- 移除了所有本地文件创建、写入、读取的逻辑,直接通过
MultipartFile.getInputStream()获取文件流构造ZipInputStream,全程在内存中处理无磁盘IO - 修正了原代码中单个文件内容被拆分为多个列表项的问题:每个压缩包内的文件会读取完整内容后再转为字符串存入列表
- 使用try-with-resources语法自动关闭流,不需要手动处理流关闭逻辑,避免资源泄漏
- 新增了目录跳过逻辑,避免压缩包内的目录项被当作空文件处理
- 显式指定了解压和字符串转换的字符集,避免不同环境下的乱码问题,可根据实际xml的编码调整
StandardCharsets.UTF_8为对应字符集
内容的提问来源于stack exchange,提问作者Amara
相关产品推荐
相关产品推荐

