如何在Java中使用Spring解压缩上传的zip文件

Nag*_*aga 4 java spring-mvc

我正在从屏幕上传zip文件夹,并使用MultipartFile将其发送到contoller。我正在尝试提取上传的文件夹并将提取的文件夹保存在某个特定位置..我?这是我的代码

 public  String test(
                @RequestParam("datafile") MultipartFile file
    { 

    String source =file.getOriginalFilename();

    //source variable will containthe value as "zip_Folder.zip";
            String destination = "D:\\destination";

            try {
                 ZipFile zipFile = new ZipFile(source);
                 zipFile.extractAll(destination);

            } catch (ZipException e) {
                e.printStackTrace();
            }
    }
Run Code Online (Sandbox Code Playgroud)

mar*_*osh 6

必需的zip4jApache Commons-IO依赖项:

@PostMapping("/upload")
public String add(@RequestParam("file") MultipartFile file) throws IOException {

    /**
     * save file to temp
     */
    File zip = File.createTempFile(UUID.randomUUID().toString(), "temp");
    FileOutputStream o = new FileOutputStream(zip);
    IOUtils.copy(file.getInputStream(), o);
    o.close();

    /**
     * unizp file from temp by zip4j
     */
    String destination = "D:\\destination";
    try {
         ZipFile zipFile = new ZipFile(zip);
         zipFile.extractAll(destination);
    } catch (ZipException e) {
        e.printStackTrace();
    } finally {
        /**
         * delete temp file
         */
        zip.delete();
    }

    return "redirect:/";
}
Run Code Online (Sandbox Code Playgroud)

除此之外,最好的方法是在属性文件中放置“ D:\ destination”之类的常量,并通过@Value注入

@Value("${destination.dir}")
private String destination;
Run Code Online (Sandbox Code Playgroud)