java导出多个xml文件的压缩zip

news/2024/7/9 23:39:42 标签: java, xml, vue
xmlns="http://www.w3.org/2000/svg" style="display: none;">

代码:

java">		// 设置响应头
        response.setCharacterEncoding("UTF-8");//设置响应的字符编码为UTF-8
        response.setContentType("application/octet-stream");//设置响应的内容类型为二进制流,通常用于文件下载。
        response.setHeader("Content-Disposition", "attachment; filename=test.zip");//设置响应头中的Content-Disposition字段,告诉浏览器将响应内容作为附件处理,并指定下载文件的名称为test.zip。
        //创建xml文件1
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        Element test = root.addElement("test");
        test.addAttribute("name","淫龙公子");
        test.addAttribute("age","38");
        test.addAttribute("jjMaxLength","6cm");
        Element test1 = root.addElement("test");
        test1.addAttribute("name","yi龙公子");
        test1.addAttribute("age","66");
        test1.addAttribute("jjMaxLength","7cm");
        Element test2 = root.addElement("test");
        test2.addAttribute("name","王有");
        test2.addAttribute("age","77");
        test2.addAttribute("jjMaxLength","1cm");
        //创建xml文件2
        Document document1 = DocumentHelper.createDocument();
        Element root1 = document1.addElement("root");
        Element test11 = root1.addElement("test");
        test11.addAttribute("name","淫龙公子");
        test11.addAttribute("age","38");
        test11.addAttribute("jjMaxLength","6cm");
        Element test12 = root1.addElement("test");
        test12.addAttribute("name","yi龙公子");
        test12.addAttribute("age","66");
        test12.addAttribute("jjMaxLength","7cm");
        Element test13 = root1.addElement("test");
        test13.addAttribute("name","王有");
        test13.addAttribute("age","77");
        test13.addAttribute("jjMaxLength","1cm");
        //创建xml文件3
        Document document2 = DocumentHelper.createDocument();
        Element root2 = document2.addElement("root");
        Element test21 = root2.addElement("test");
        test21.addAttribute("name","淫龙公子");
        test21.addAttribute("age","38");
        test21.addAttribute("jjMaxLength","6cm");
        Element test22 = root2.addElement("test");
        test22.addAttribute("name","yi龙公子");
        test22.addAttribute("age","66");
        test22.addAttribute("jjMaxLength","7cm");
        Element test23 = root2.addElement("test");
        test23.addAttribute("name","王有");
        test23.addAttribute("age","77");
        test23.addAttribute("jjMaxLength","1cm");
        // 将XML转成字符串,后面能用工具类将字符串转成流
        String asXML = document.asXML();
        String asXML1 = document1.asXML();
        String asXML2 = document2.asXML();
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(response.getOutputStream());
            //writeToZip:将xml流写到zip输出流中
            writeToZip(out,asXML,"test1.xml");
            writeToZip(out,asXML1,"test2.xml");
            writeToZip(out,asXML2,"test3.xml");
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

writeToZip方法:

java">private void writeToZip(ZipOutputStream out,String xmlContent,String fileName) throws IOException {
        int len =0;
        byte[] buffer = new byte[1024];
        InputStream is = IOUtils.toInputStream(xmlContent, "utf-8");

            out.putNextEntry(new ZipEntry(fileName));
            while ((len = is.read(buffer)) >0){
                out.write(buffer,0,len);
            }

        out.closeEntry();
        is.close();

    }

注意:前后端分离项目中如果前端有响应拦截器,我们需要再做处理,例如vue项目的下载方法:

javascript">// 通用下载方法
export function download(url, params, filename, config) {
  downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", })
  return service.post(url, params, {
    transformRequest: [(params) => { return tansParams(params) }],
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    responseType: 'blob',
    ...config
  }).then(async (data) => {
    const isBlob = blobValidate(data);
    if (isBlob) {
      const blob = new Blob([data])
      saveAs(blob, filename)
    } else {
      const resText = await data.text();
      const rspObj = JSON.parse(resText);
      const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
      Message.error(errMsg);
    }
    downloadLoadingInstance.close();
  }).catch((r) => {
    console.error(r)
    Message.error('下载文件出现错误,请联系管理员!')
    downloadLoadingInstance.close();
  })
}

附加(导出xml文件):

java">//导出xml文件
        // 设置响应头
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=test.xml");
        //创建xml文件
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("root");
        Element test = root.addElement("test");
        test.addAttribute("name","淫龙公子");
        test.addAttribute("age","38");
        test.addAttribute("jjMaxLength","6cm");
        Element test1 = root.addElement("test");
        test1.addAttribute("name","yi龙公子");
        test1.addAttribute("age","66");
        test1.addAttribute("jjMaxLength","7cm");
        Element test2 = root.addElement("test");
        test2.addAttribute("name","王有");
        test2.addAttribute("age","77");
        test2.addAttribute("jjMaxLength","1cm");
        try {
            OutputStream outputStream = response.getOutputStream();
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(outputStream, format);
            writer.write(document);
            writer.close();
            outputStream.flush();
            outputStream.close();
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

用到的jar包:

xml"><!-- xml包 -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.1</version>
        </dependency>

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

相关文章

[蓝桥杯 2023 省 B] 冶炼金属

P9240 [蓝桥杯 2023 省 B] 冶炼金属 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 参考题解&#xff1a; #C3150——蓝桥杯2023年第十四届省赛真题-冶炼金属(分块)-Dotcpp编程社区 https://www.bilibili.com/video/BV1wc411x7KU/?spm_id_from333.1007.top_right_bar_windo…

基于springboot+vue的党员教育和管理系统

博主主页&#xff1a;猫头鹰源码 博主简介&#xff1a;Java领域优质创作者、CSDN博客专家、阿里云专家博主、公司架构师、全网粉丝5万、专注Java技术领域和毕业设计项目实战&#xff0c;欢迎高校老师\讲师\同行交流合作 ​主要内容&#xff1a;毕业设计(Javaweb项目|小程序|Pyt…

iview碰到的一些问题总结

iview tabs嵌套使用问题 tabs嵌套使用的时候不是直接套用行了&#xff0c;直接套用会出现内层tab都集成到一级tab去&#xff0c;需要设置该属性指向对应 Tabs 的 name 字段(需要版本大于3.3.1) <Tabs name"tab1" ><TabPane label"标签1" tab&qu…

洛谷P1059 [NOIP2006 普及组] 明明的随机数

题目描述 明明想在学校中请一些同学一起做一项问卷调查&#xff0c;为了实验的客观性&#xff0c;他先用计算机生成了 N 个 1 到 1000 之间的随机整数 (N≤100)&#xff0c;对于其中重复的数字&#xff0c;只保留一个&#xff0c;把其余相同的数去掉&#xff0c;不同的数对应着…

分分钟搞定JSON解析

json 库能够解析字符串或文本中的 JSON 内容。 该库将 JSON 解析为 Python 字典或列表&#xff0c;也能将 Python 字典或列表转换为 JSON 字符串。 解析 JSON 如下的 JSON 格式的字符串&#xff1a; json_string {"first_name": "Guido", "last_na…

Java基础 - 6 - 面向对象(二)

Java基础 - 6 - 面向对象&#xff08;一&#xff09;-CSDN博客 二. 面向对象高级 2.1 static static叫做静态&#xff0c;可以修饰成员变量、成员方法 2.1.1 static修饰成员变量 成员变量按照有无static修饰&#xff0c;分为两种&#xff1a;类变量、实例变量&#xff08;对象…

Android 中的 LinearLayout 布局

在 Android 开发中&#xff0c;布局是至关重要的一部分&#xff0c;它决定了应用程序的界面结构和用户体验。LinearLayout 是 Android 中最常用的布局之一&#xff0c;它以线性方式排列子视图&#xff0c;可以垂直或水平布局。在这篇博客中&#xff0c;我们将深入了解 LinearLa…

每天一个数据分析题(一百七十九)

指标体系包括根指标、组合指标和派生指标。业务方最关心的指标称为根指标&#xff0c;根指标与最常用的维度取值相结合生成组合指标&#xff0c;根指标和组合指标的运算得到派生指标。以下属于派生指标的是&#xff08;&#xff09;单选 A. 销售额 B. 净利润 C. 客单价 D. …