日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

SpringBoot批量下載壓縮包的實(shí)現(xiàn)

作者:多放香菜少加蔥 更新時(shí)間: 2022-07-21 編程語言

controller 代碼

@ApiOperation(value = "系統(tǒng)文件批量下載接口", produces = "application/octet-stream")
    @PostMapping(value = "/downloadzip")
    public void downloadzip(@ApiParam("文件 url 路徑") @RequestBody CommonProjectSearchVo searchVo, HttpServletResponse response) throws Exception {
        String[] paths = searchVo.getPaths();
        if (Objects.isNull(searchVo) || Objects.isNull(searchVo.getPaths()) || paths.length == 0) {
            throw new CustomException("請選擇附件");
        }
        if (paths.length != 0) {
            // 創(chuàng)建臨時(shí)路徑,存放壓縮文件
            String myFileName = OperatorUtils.getOperator().getOperator()
                    + String.valueOf(new Date().getTime()) + ".zip";
            String zipFilePath = downloadPath + "/" + myFileName;
 
            File file = new File(downloadPath);
            //如果文件夾不存在則創(chuàng)建
            if (!file.exists() && !file.isDirectory()) {
                file.mkdir();
            }
            // 壓縮輸出流,包裝流,將臨時(shí)文件輸出流包裝成壓縮流,將所有文件輸出到這里,打成zip包
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
            // 循環(huán)調(diào)用壓縮文件方法,將一個(gè)一個(gè)需要下載的文件打入壓縮文件包
            for (String path : paths) {
                FileConvertUtil.fileToZip(path, zipOut);
            }
            // 壓縮完成后,關(guān)閉壓縮流
            zipOut.close();
 
            //拼接下載默認(rèn)名稱并轉(zhuǎn)為ISO-8859-1格式
            String fileName = new String((myFileName).getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attchment;filename=" + fileName);
 
            //該流不可以手動(dòng)關(guān)閉,手動(dòng)關(guān)閉下載會(huì)出問題,下載完成后會(huì)自動(dòng)關(guān)閉
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(zipFilePath);
            // 如果是SpringBoot框架,在這個(gè)路徑
            // org.apache.tomcat.util.http.fileupload.IOUtils產(chǎn)品
            // 否則需要自主引入apache的 commons-io依賴
            // copy方法為文件復(fù)制,在這里直接實(shí)現(xiàn)了下載效果
            IOUtils.copy(inputStream, outputStream);
 
            // 關(guān)閉輸入流
            inputStream.close();
 
            //下載完成之后,刪掉這個(gè)zip包
            File fileTempZip = new File(zipFilePath);
            fileTempZip.delete();
        }
    }

工具類FileConvertUtil.fileToZip

/**
 * 文件格式轉(zhuǎn)換工具類
 */
public class FileConvertUtil {
 
    /**
     * 【文件壓縮】網(wǎng)絡(luò)文件
     *
     * @param filePath:
     * @param zipOut:
     * @return void
     */
    public static void fileToZip(String filePath, ZipOutputStream zipOut) throws IOException {
        filePath = getEncodeUrl(filePath).replaceAll("\\+", "%20");
        // 需要壓縮的文件
        File file = new File(filePath);
        // 獲取文件名稱,為解決壓縮時(shí)重復(fù)名稱問題,對文件名加時(shí)間戳處理
        String fileName = FilenameUtils.getBaseName(URLDecoder.decode(file.getName(), "UTF-8")) + "-"
                + String.valueOf(new Date().getTime()) + "."
                + FilenameUtils.getExtension(file.getName());
        InputStream fileInput = getInputStream(filePath);
        // 緩沖
        byte[] bufferArea = new byte[1024 * 10];
        BufferedInputStream bufferStream = new BufferedInputStream(fileInput, 1024 * 10);
        // 將當(dāng)前文件作為一個(gè)zip實(shí)體寫入壓縮流,fileName代表壓縮文件中的文件名稱
        zipOut.putNextEntry(new ZipEntry(fileName));
        int length = 0;
        // 最常規(guī)IO操作,不必緊張
        while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write(bufferArea, 0, length);
        }
        //關(guān)閉流
        fileInput.close();
        // 需要注意的是緩沖流必須要關(guān)閉流,否則輸出無效
        bufferStream.close();
        // 壓縮流不必關(guān)閉,使用完后再關(guān)
    }
 
    /**
     * 【獲取網(wǎng)絡(luò)文件的輸入流】
     *
     * @param filePath: 網(wǎng)絡(luò)文件路徑
     * @return java.io.InputStream
     */
    public static InputStream getInputStream(String filePath) throws IOException {
        InputStream inputStream = null;
        // 創(chuàng)建URL
        URL url = new URL(filePath);
        // 試圖連接并取得返回狀態(tài)碼
        URLConnection urlconn = url.openConnection();
        urlconn.connect();
        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
        int httpResult = httpconn.getResponseCode();
        if (httpResult == HttpURLConnection.HTTP_OK) {
            inputStream = urlconn.getInputStream();
        }
        return inputStream;
    }
 
}

原文鏈接:https://blog.csdn.net/qq_41512902/article/details/125842512

欄目分類
最近更新