You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解压请求中的.tar.gz格式MultipartFile并添加至List<File>

解压.tar.gz格式MultipartFile并收集文件到List

要实现需求,你需要将TarArchiveEntry中的内容写入本地临时文件,再将这些临时文件加入List<File>。注意跳过目录条目,同时用try-with-resources自动管理流资源避免泄漏。以下是完整实现代码:

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;

@RequestMapping(value="/importFile", produces="application/json", method=RequestMethod.POST)
@ResponseBody
public ca.alea.cam.api.model.Response importFile(@RequestBody MultipartFile file) throws ContentRepositoryDaoException, Exception {
    List<File> fileList = new ArrayList<>();
    
    // 用try-with-resources自动关闭所有流
    try (InputStream in = file.getInputStream();
         GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in);
         TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {
        
        TarArchiveEntry entry;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            // 跳过目录,只处理文件
            if (!entry.isFile()) {
                continue;
            }
            
            // 创建临时文件,自动添加前缀后缀避免重名
            File tempFile = File.createTempFile("tar_", "_" + entry.getName());
            tempFile.deleteOnExit(); // JVM退出时自动清理临时文件
            
            // 将压缩包内的文件内容写入临时文件
            try (OutputStream out = new FileOutputStream(tempFile)) {
                IOUtils.copy(tarIn, out);
            }
            
            // 将生成的临时文件加入集合
            fileList.add(tempFile);
        }
    }
    
    // 后续可根据业务逻辑处理fileList
    return new ca.alea.cam.api.model.Response(); // 替换为实际业务返回结果
}

注意事项

  • 若不需要临时文件自动清理,可去掉deleteOnExit(),改为业务流程结束后手动删除或保留到指定目录。
  • 也可以用Java 7+的Files.copy(tarIn, tempFile.toPath())替代IOUtils.copy,无需依赖commons-io。
  • 必须判断entry.isFile()跳过目录,否则会生成空文件或引发写入异常。

内容的提问来源于stack exchange,提问作者user1971376

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 21:45:36