溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何使用SpringBoot將文件打包成zip存放或?qū)С?/h1>
發(fā)布時間:2021-06-12 09:18:15 來源:億速云 閱讀:706 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹如何使用SpringBoot將文件打包成zip存放或?qū)С?,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

環(huán)境準備

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

如何使用SpringBoot將文件打包成zip存放或?qū)С?></p><h3>將文件打包成Zip存放</h3><p><strong>代碼</strong></p><p><strong>Controller</strong>代碼:</p><pre class=@RequestMapping("/zip") @RestController public class ZipController {     /**      * 將文件打包成zip并存放在特定位置      */     @PostMapping("package")     public void packageFileToZip() throws IOException {         // 為了方便我直接將文件地址寫好了,各位可以根據(jù)自己的情況修改         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盤創(chuàng)建一個壓縮包         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:

如何使用SpringBoot將文件打包成zip存放或?qū)С?></p><p>調(diào)用接口后就會在D盤中新建一個package.zip的壓縮包:</p><p><img src=/**      * 將文件打包成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 {
            // 關(guān)閉流
            try {
                if (bufferedInputStream != null) {
                    bufferedInputStream.close();
                }
                if (zipOutputStream != null ) {
                    zipOutputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

測試

還是用postman:

如何使用SpringBoot將文件打包成zip存放或?qū)С?><br/><img src=以上是“如何使用SpringBoot將文件打包成zip存放或?qū)С觥边@篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI