首頁 > 軟體

手把手教你用SpringBoot將檔案打包成zip存放或匯出

2021-06-11 19:00:23

環境準備

其實也沒什麼準備,準備好Springboot就行,還有幾張圖片:

將檔案打包成Zip存放

程式碼

Controller程式碼:

@RequestMapping("/zip")
@RestController
public class ZipController {

    /**
     * 將檔案打包成zip並存放在特定位置
     */
    @PostMapping("package")
    public void packageFileToZip() throws IOException {
        // 為了方便我直接將檔案地址寫好了,各位可以根據自己的情況修改
        String[] filePath = new String[]{"E:\ykds\1068128498917799516.jpg", "E:\ykds\1068128498917917980.jpg", "E:\ykds\1068128498917807874.jpg"};
        // 將需要打包的檔案都放在一個集合中
        List<File> fileList = new ArrayList<>();
        for (String s : filePath) {
            File file = new File(s);
            fileList.add(file);
        }
        // 先在D槽建立一個壓縮包
        File zipFile = new File("D:\package.zip");
        if(!zipFile.exists())
            zipFile.createNewFile();
        // 將package.zip的File物件傳到toZip物件中
        ZipUtils.toZip(fileList, zipFile);
    }
}

ZipUTils工具類程式碼

public class ZipUtils {

    /**
     * 把檔案集合打成zip壓縮包
     * @param srcFiles 壓縮檔案集合
     * @param zipFile  zip檔名
     * @throws RuntimeException 異常
     */
    public static void toZip(List<File> srcFiles, File zipFile) throws IOException {
        if(zipFile == null){
            return;
        }
        if(!zipFile.getName().endsWith(".zip")){
            return;
        }
        ZipOutputStream zos = null;
        FileOutputStream out = new FileOutputStream(zipFile);
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                // 讀取檔案並寫入到zip中
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                    zos.flush();
                }
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (zos != null) {
                zos.close();
            }
        }
    }
}

測試

程式碼打好了,接下來測試下,開啟熟悉的postman:

呼叫介面後就會在D槽中新建一個package.zip的壓縮包:

可以看到,我打包的檔案都在這裡,再看看能不能正常顯示:

very good!

將檔案打包成zip並匯出

上面的方法只是將壓縮包儲存在本地,如果需要匯出的話程式碼有點不一樣。

程式碼

Controller程式碼:

/**
     * 將檔案打包成zip並下載
     */
    @PostMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 這裡還是和上面一樣
        String[] filePath = new String[]{"E:\ykds\1068128498917799516.jpg", "E:\ykds\1068128498917917980.jpg", "E:\ykds\1068128498917807874.jpg"};
        List<File> fileList = new ArrayList<>();
        for (String s : filePath) {
            File file = new File(s);
            fileList.add(file);
        }
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=download.zip");
        ZipUtils.downloadZip(response.getOutputStream(), fileList);
    }

ZipUtils工具類程式碼

public static void downloadZip(OutputStream outputStream, List<File> fileList){
        BufferedInputStream bufferedInputStream = null;
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(outputStream);
            for (File file : fileList) {
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);
                byte[] buf = new byte[BUFFER_SIZE];
                int len;
                FileInputStream in = new FileInputStream(file);
                while ((len = in.read(buf)) != -1) {
                    zipOutputStream.write(buf, 0, len);
                    zipOutputStream.flush();
                }
            }
            zipOutputStream.flush();
            zipOutputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉流
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (zipOutputStream != null ) {
                    zipOutputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

測試

還是用postman:


下載完成後開啟看看

到此這篇關於手把手教你用SpringBoot將檔案打包成zip存放或匯出的文章就介紹到這了,更多相關SpringBoot將檔案打包成zip內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com