簡體   English   中英

如何在Java中使用Spring解壓縮上傳的zip文件

[英]how to unzip an uploaded zip file using spring in java

我正在從屏幕上傳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();
            }
    }

必需的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:/";
}

除此之外,最好的方法是在屬性文件中放置“ D:\\ destination”之類的常量,並通過@Value注入

@Value("${destination.dir}")
private String destination;

嘗試使用

java.util.zip.ZipEntry; java.util.zip.ZipInputStream;

為我工作

https://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM