导出数据为zip压缩文件,解压后为json文件

news/2024/7/24 12:11:16 标签: json
  1. 前端只要将要导出的数据的ids传回后端就行了

比如

    handleExportApp(row) {
      const ids = row ? [row.id] : this.checkedRows.map(v => v.id); 
      //exportApp为后端导出接口
      exportApp(ids.join(","));
    },
  1. 后端接口
    public void exportApp(String ids, HttpServletResponse response) {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<App> list = appService.findAppAllListByIds(idsList);
        //创建HttpServerResponse的输出流
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            BufferedInputStream bis;
            File file = new File("应用数据包.zip");
            //通过ZipOutputStream定义要写入的对象
            ZipOutputStream zos = null;
            zos = new ZipOutputStream(new FileOutputStream(file));
            writeZos(list, zos);
            zos.close();
            //定义返回类型
            response.setContentType("text/html; charset=UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("应用数据包.zip", "UTF-8"))));
            bis = new BufferedInputStream(new FileInputStream(file));
            //定义byte,长度就是要转成zip文件的byte长度,避免浪费资源
            byte[] buffer = new byte[bis.available()];
            bis.read(buffer);
            out.flush();
            out.write(buffer);
            file.delete();
        } catch (IOException e) {
            logger.error("应用数据包流写入异常{}", e.getMessage());
            throw new BusinessException("系统异常");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
     }



    public void writeZos(List<App> list, ZipOutputStream zos) {
        list.forEach(a -> {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try {
                byteArrayOutputStream.write(JSONUtil.toJsonStr(a).getBytes());
                zos.putNextEntry(new ZipEntry(a.getName() + ".json"));
                byte[] excelStream = byteArrayOutputStream.toByteArray();
                zos.write(excelStream);
                zos.closeEntry();
            } catch (IOException e) {
                logger.error("应用数据包流写入异常{}", e.getMessage());
                throw new BusinessException("系统异常");
            }
        });
    }

拓展
如果只是导出json文件,不需要压缩包的话
前端

    handleExportApp(row) {
      this.ids = row ? [row.id] : this.checkedRows.map(v => v.id);
      this.loading = true;
      this.exportData(this.ids);
    },

    exportData(ids) {
      if (ids.length > 0) {
        const currentId = ids.shift(); // 取出数组中的第一个id
        simulateClick(exportApp(currentId)); // 导出单个数据
        setTimeout(() => {
          this.exportData(ids); // 递归调用导出函数,继续下一个数据
        }, 10000); // 设置递归的间隔时间,以免处理过多数据造成性能问题
      }
    },

后端

        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));

        for (String id : idsList) {
            App app = appService.getById(id);

            // 忽略未找到的应用程序
            if (app == null) {
                continue;
            }
            ObjectMapper objectMapper = new ObjectMapper();
            try {
            	//把对象转成json字符串
                String jsonString = objectMapper.writeValueAsString(app);

                // 设置响应头部信息
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("应用_" + app.getName() + ".json", "UTF-8"))));

                // 获取输出流并写入JSON字符串
                PrintWriter writer = response.getWriter();
                writer.write(jsonString);
                writer.flush();
                writer.close();
            } catch (IOException e) {
                logger.error("导出应用数据异常:{}", e.getMessage());
                throw new BusinessException("系统异常");
            }
        }

但是这样有一个不好的地方,就是前端用户体验感不是很好,需要等待前端一个个文件导出。


http://www.niftyadmin.cn/n/5158326.html

相关文章

多模态中各种Fusion方式汇总

多模态中各种Fusion骚操作 大噶好&#xff0c;我是DASOU&#xff1b; 今天继续写多模态系列文章&#xff0c;对多模态感兴趣的可以看我之前的文章&#xff1a; 其实对于多模态来说&#xff0c;主要可以从三个部分去掌握它&#xff1a; 如何获取多模态的表示【learning mult…

年营收增长30%起!武汉迪赛威用飞桨助推智慧执法

智慧执法已成为建设文明城市不可忽视的环节。而“智慧执法”这四个字背后&#xff0c;却是社会治理中无穷无尽的需要考虑和衡量的微小细节。有时候&#xff0c;仅仅是一个环节的改进&#xff0c;就能节省极大的人力物力财力。 例如&#xff0c;“随身物品智能识物终端”&#…

uni-app android js判断数值是否是数组

判断是否是数组有的方法不适用&#xff0c;如instanceof 推荐的解决方式&#xff1a; Object.prototype.toString.call(value) [object Array]

centerOS卸载nginx

一、检查Nginx是否已经安装 在卸载Nginx之前&#xff0c;需要确认Nginx是否已经安装在系统中。可以通过执行以下命令检查&#xff1a; nginx -v二、卸载Nginx 如果Nginx已经安装&#xff0c;可以执行以下步骤卸载&#xff1a; 停止Nginx服务 在卸载Nginx之前&#xff0c;需要…

扩大图片手势的点击范围的方法

如果项目中有需求&#xff0c;图片添加手势的范围&#xff0c;那么可以用以下的方法&#xff1a; // 计算扩大点击区域的大小 CGFloat expandedInsets 10.0; // 自定义的扩大值 // 创建一个扩大点击区域的矩形 CGRect expandedFrame CGRectInset(self.cancelButton.frame, …

D - Wall Painting

思路&#xff1a; &#xff08;1&#xff09;条件问题&#xff1a;给定n个数&#xff0c;求其中任意k个数的组合的异或和&#xff0c;k取1~n全部求一遍&#xff1b; &#xff08;2&#xff09;分析&#xff1a; 凡是异或率先考虑二进制&#xff0c;由于求的是所有情况的异或…

分享34个发布商会PPT,总有一款适合您

分享34个发布商会PPT&#xff0c;总有一款适合您 链接&#xff1a;https://pan.baidu.com/s/1jP9toqTZONWeDIcxvw1wxg?pwd8888 提取码&#xff1a;8888 Python采集代码下载链接&#xff1a;采集代码.zip - 蓝奏云 学习知识费力气&#xff0c;收集整理更不易。知识付费甚…

esxi 6.7下安装黑裙

esxi上创建一个黑裙系统的虚拟机&#xff0c;用来存资料 一、工具 硬件&#xff1a; 工控机&#xff1a;装有esxi6.7系统&#xff08;192.168.100.2&#xff09;&#xff0c;配置&#xff1a;3865U&#xff0c;16G内存&#xff0c;120Gmsata120sata硬盘&#xff0c;6个网口 主…