栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Vue+SpringBoot导出文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Vue+SpringBoot导出文件

Vue+SpringBoot导出文件并触发浏览器下载

前端使用Vue2.0 后端使用SpringBoot2 后端实现信息的导出并触发前端浏览器下载功能

后端实现

将data写入输出流,并response设置参数触发浏览器下载

public class ExportTxt {

    public static void export(HttpServletResponse response, TxtData data) throws Exception {
        String filename = data.getFileName() + "-" + (new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())) + ".txt";
        filename = URLEncoder.encode(filename, "utf-8");
        response.setHeader("content-Type", "text/plain");
        // 下载文件的默认名称
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        response.addHeader("filename", filename);
        response.addHeader("returncode","0000");
        exportTxt(data, response.getOutputStream());
    }

    public static void exportTxt(TxtData data, OutputStream out) throws Exception {
        List> maps = data.getData();
        try {
            for (Map map : maps) {
                String no = map.get("no").toString();
                String message = map.get("message").toString();
                String info = no + " : " + message + "n";
                //写入输出流
                byte[] bytes = info.getBytes();
                out.write(bytes);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

}

此外还可以自定义封装数据结构

@Data
public class TxtData {

    // 错误行数-错误信息
    private List> data;

    // 导出的文件名
    private String fileName;

}
前端实现
this.action(this.form).then(res => {
        this.$waiting.close()
        if (window.navigator && window.navigator.msSaveBlob) {//ie浏览器
          window.navigator.msSaveBlob(res.data, decodeURIComponent(res.filename));
        } else if (window.URL && window.URL.createObjectURL) {//其他浏览器
          let url = window.URL.createObjectURL(res.data)
          let a = document.createElement('a')
          a.href = url
          a.download = decodeURIComponent(res.filename)
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        } else {
          this.$alert('您的浏览器不支持下载此文件', '下载文件失败', { type: 'error' })
        }
      }).catch(err => {
        this.$waiting.close()
        this.$alert(err, '导出数据失败', { type: 'error' })
      })
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781551.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号