Java生成Json文件添加到ZIP压缩并导出

Java实践 专栏收录该内容
4 篇文章 0 订阅

Java生成Json文件添加到ZIP压缩并导出

前言

     需要根据在前端选择的文件列表生产Json文件并导出Zip文件

代码说明

     前端部分的方法:

    // 导出选中的文件
    exportFiles() {
        this.fileIdList = [];
        for (let i = 0; i < this.multipleSelection.length; i++) {
            this.fileIdList.push(this.multipleSelection[i].fileId);
        }
        const response = dataExport(this, this.fileIdList);
        let blob = new Blob([response.data], {
            type: 'application/zip'
        });
        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob)
        } else {
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(blob);
            link.click();
            window.URL.revokeObjectURL(link.href); //释放内存
        }
    },
	export const dataExport = (vueObject, dataIdList) => getDataRaw(vueObject, url);
	
	export function getDataRaw(vueObject, url) {
	    return new Promise((resolve) => {
	        const config = {};
	        config['responseType'] = 'blob';
	        Vue.prototype.$http.get(url, config)
	            .then(res => {
	                console.log(res);
	                resolve(res)
	            })
	    });
	}

     后端部分代码如下:

    @GetMapping("export/{fileIdList}")
    @ApiOperation(value = "导出ZIP文件", notes = "参数:fileIdList"
    public void export(@PathVariable("fileIdList") String fileIdList, HttpServletResponse response) {
        try {
            String[] dataIdList = fileIdList.split(",");
            String baseAddress = System.getProperty("java.io.tmpdir");
            String folder = IDGenerator.idCreated(6, 0);
            // 根据Id生成对应Json文件
            if (dataIdList != null && dataIdList.length > 0) {
                for (String ids : dataIdList) {
                    int id = Integer.valueOf(ids);
                    FileInfo fileInfo = fileInfoService.getById(id);
                    exportFileVO.setData(fileInfo);
                    String jsonString = JSON.toJSONString(exportFileVO, SerializerFeature.WriteMapNullValue);
                    FileUtils.createFile(baseAddress + folder + "/", fileInfo.getFileName() + ".json", jsonString);
                }
            }
            // 将文件夹压缩为ZIP文件
            String zipFile = baseAddress + folder + ".zip";
            FileUtils.compress(baseAddress + folder, zipFile);
            File file = new File(zipFile);
            FileInputStream inputStream = new FileInputStream(file);
            // 导出Zip文件
            byte[] data = new byte[(int) file.length()];
            inputStream.read(data);
            inputStream.close();
            response.setHeader("content-type", "application/octet-stream;charset=ISO8859-1");
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.addHeader("Content-Length", "" + file.length());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(folder + ".zip", "UTF-8"));
            OutputStream stream = response.getOutputStream();
            stream.write(data);
            stream.flush();
            stream.close();
            // 删除文件夹及压缩文件
            FileUtils.deleteDir(baseAddress + folder);
            FileUtils.deleteDir(zipFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

小结

      很常见的一个功能需求,整理方法做一次总结,荣幸与您分享~

  • 0
    点赞
  • 1
    评论
  • 1
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

相关推荐
©️2020 CSDN 皮肤主题: 程序猿惹谁了 设计师:白松林 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值