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

學無先后,達者為師

網站首頁 編程語言 正文

SpringBoot批量下載壓縮包的實現

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

controller 代碼

@ApiOperation(value = "系統文件批量下載接口", 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) {
            // 創建臨時路徑,存放壓縮文件
            String myFileName = OperatorUtils.getOperator().getOperator()
                    + String.valueOf(new Date().getTime()) + ".zip";
            String zipFilePath = downloadPath + "/" + myFileName;
 
            File file = new File(downloadPath);
            //如果文件夾不存在則創建
            if (!file.exists() && !file.isDirectory()) {
                file.mkdir();
            }
            // 壓縮輸出流,包裝流,將臨時文件輸出流包裝成壓縮流,將所有文件輸出到這里,打成zip包
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFilePath));
            // 循環調用壓縮文件方法,將一個一個需要下載的文件打入壓縮文件包
            for (String path : paths) {
                FileConvertUtil.fileToZip(path, zipOut);
            }
            // 壓縮完成后,關閉壓縮流
            zipOut.close();
 
            //拼接下載默認名稱并轉為ISO-8859-1格式
            String fileName = new String((myFileName).getBytes(), "ISO-8859-1");
            response.setHeader("Content-Disposition", "attchment;filename=" + fileName);
 
            //該流不可以手動關閉,手動關閉下載會出問題,下載完成后會自動關閉
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(zipFilePath);
            // 如果是SpringBoot框架,在這個路徑
            // org.apache.tomcat.util.http.fileupload.IOUtils產品
            // 否則需要自主引入apache的 commons-io依賴
            // copy方法為文件復制,在這里直接實現了下載效果
            IOUtils.copy(inputStream, outputStream);
 
            // 關閉輸入流
            inputStream.close();
 
            //下載完成之后,刪掉這個zip包
            File fileTempZip = new File(zipFilePath);
            fileTempZip.delete();
        }
    }

工具類FileConvertUtil.fileToZip

/**
 * 文件格式轉換工具類
 */
public class FileConvertUtil {
 
    /**
     * 【文件壓縮】網絡文件
     *
     * @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);
        // 獲取文件名稱,為解決壓縮時重復名稱問題,對文件名加時間戳處理
        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);
        // 將當前文件作為一個zip實體寫入壓縮流,fileName代表壓縮文件中的文件名稱
        zipOut.putNextEntry(new ZipEntry(fileName));
        int length = 0;
        // 最常規IO操作,不必緊張
        while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write(bufferArea, 0, length);
        }
        //關閉流
        fileInput.close();
        // 需要注意的是緩沖流必須要關閉流,否則輸出無效
        bufferStream.close();
        // 壓縮流不必關閉,使用完后再關
    }
 
    /**
     * 【獲取網絡文件的輸入流】
     *
     * @param filePath: 網絡文件路徑
     * @return java.io.InputStream
     */
    public static InputStream getInputStream(String filePath) throws IOException {
        InputStream inputStream = null;
        // 創建URL
        URL url = new URL(filePath);
        // 試圖連接并取得返回狀態碼
        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

欄目分類
最近更新