java多個文件打包成zip格式下載


我們在使用java下載時候,通常是通過路徑獲取二進制文件,再通過HttpServletResponse發送到前台,現在將多張圖片打包成zip格式進行下載。代碼如下:

ZipOutputStream zos = null;
BufferedInputStream br = null;
//下載方法
try {
    //文件的名稱
    String downloadFilename = registrationLoginResultVo.getBusinessName()+".zip";
    response.reset();
    //設置格式
    response.setContentType("application/x-msdownload");
    response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(downloadFilename, "UTF-8"));
    //ZipOutputStream來對文件壓縮操作
    zos = new ZipOutputStream(response.getOutputStream());
    //循環下載文件,並將之放到ZipOutputStream中
    for (int i = 0; i < filePath.length; i++) {
        //filePath是下載路徑集合
        //fileName是文件名稱
        zos.putNextEntry(new ZipEntry(fileName[i]+".jpg"));
        br = new BufferedInputStream(new FileInputStream(filePath[i]));
        byte[] buffer = new byte[1024];
        int r = 0;
        while ((r = br.read(buffer)) != -1) {
            zos.write(buffer, 0, r);
        }
    }
    zos.flush();
} catch (IOException e) {
    log.error("導出圖片壓縮包錯誤", e);
}finally {
    try {
        zos.close();
        br.close();
    } catch (IOException e) {
        log.error("導出圖片關閉流異常", e);
    }
}

 

前端使用xhr進行下載

window.img = function img() {
    var supplierName = $("#businessName").val();
    layer.load(2);
    //下載圖片格式
    var fileName = supplierName+".zip";
    var url = config.base_server + "路徑?uuid="+uuid
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
        if (this.status == "200") {
            var content = this.response;
            var blob = new Blob([xhr.response]);
            //for IE
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(blob, fileName);
            } else {
                var aElem = document.createElement('a');
                aElem.download = fileName;
                aElem.href = window.URL.createObjectURL(blob);
                aElem.onload = function (e) {
                    window.URL.revokeObjectURL(aElem.href);
                };
                document.body.appendChild(aElem);
                aElem.click();
                document.body.removeChild(aElem);
            }
            layer.closeAll();
        }
    };
    xhr.setRequestHeader("Authorization", config.getToken());
    xhr.send();
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM