文件压缩下载

由于经常需要从文件存储服务器取出文件,并提供压缩并下载这个功能,简单记录一下

建立一个临时文件夹

String tempDirPath = FilenameUtils.concat(FileUtils.getTempDirectory().getPath(), UUID.randomUUID().toString());
File dir = new File(tempDirPath);
if (!dir.exists()) {
    dir.mkdir();
}

从服务器下载文件并存储在文件夹中

try (InputStream inputStream = dataStorage.getInputStream(wsxx.getWjlj())) {
    File file = new File(FilenameUtils.concat(tempDirPath, wsxx.getWjmc()));
    FileUtils.copyInputStreamToFile(inputStream, file);
} catch (StoreSystemException | IOException e) {
    log.error("{}文件下载失败", wsxx.getWjmc(), e);
}

进行压缩

// 该outputStream 是由HttpServletResponse 带出来的
try (ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream)) {
    toZip(dir, zipOutputStream);
} catch (IOException e) {
    log.error("压缩文件失败", e);
}
private void toZip(File sourceFile, ZipOutputStream zos) throws IOException {
    File[] files = sourceFile.listFiles();
    if (files != null && files.length != 0) {
        for (File file : files) {
            try (FileInputStream in = new FileInputStream(file)) {
                zos.putNextEntry(new ZipEntry(file.getName()));
                IOUtils.copy(in, zos);
            } catch (IOException e) {
                log.error("压缩文件失败", e);
            } finally {
                zos.closeEntry();
            }
        }
    }
}

controller层

@PostMapping("downloadWs")
public void downloadWs(@RequestBody WsDownloadVO wsDownloadVO, HttpServletResponse response) {
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setDateHeader("Expires", 0);
    response.setContentType("application/zip;charset=utf-8");
    try {
        response.flushBuffer();
        pljsService.downloadWs(wsDownloadVO.getXyrbh(), wsDownloadVO.getGarybh(), response.getOutputStream());
    } catch (IOException e) {
        log.error("获取文件下载输出流失败", e);
    }
}

前端接收代码

downloadWs: function () {
    var _this = this
    var fileName = "文书.zip";
    Artery.axios.post("ui/pljs/downloadWs", {'xyrbh': _this.xyrbh, 'garybh': _this.garybh}, {responseType: 'arraybuffer'}).then(function (res) {
        var blob = new Blob([res.data], {type: 'application/zip;charset=utf-8'})
        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName);
        } else {
            var link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            window.URL.revokeObjectURL(link.href);
        }
    })
}

零零碎碎就这些吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值