vue~使用axios实现excel文件下载的实现

前端VUE页面上的导出或者下载功能,一般是调用后端的一个接口,由接口生成excel,word这些文件的流信息,返回给vue,然后由vue去构建下载的动作,这边整理了一下,封装了一下,方便以后复用。

封装一个download文件

使用年月日时分秒毫秒做为文件的名称,下载为excel文件

/**
 * 下载文件
 */
export const downloadFile = (url,ext, params) => {
    let accessToken = getStore('accessToken');
    return axios({
        method: 'get',
        url: `${base}${url}`,
        params: params,
        headers: {
            'accessToken': accessToken
        },
        responseType: 'blob', //二进制流
    }).then(res => {
        // 处理返回的文件流
        const content = res;
        const blob = new Blob([content], { type: 'application/vnd.ms-excel;charset=utf-8' });
        var date =
            new Date().getFullYear() +
            "" +
            (new Date().getMonth() + 1) +
            "" +
            new Date().getDate() +
            "" +
            new Date().getHours() +
            "" +
            new Date().getMinutes() +
            "" +
            new Date().getSeconds() +
            "" +
            new Date().getMilliseconds();
        const fileName = date + "." + ext;
        if ("download" in document.createElement("a")) {
            // 非IE下载
            const elink = document.createElement("a");
            elink.download = fileName;
            elink.style.display = "none";
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName);
        }
    });
};

为具体功能封装一个组件,方便在前台调用


// 评价导出
export const getRecordExport= (params) => {
    return downloadFile('/record/export',"xlsx", params)
}

vue页面上调用它,实现导出

<script>
import {
  getReportExport
} from "@/api/index";
import util from "@/libs/util.js";

export default {
  name: "task-manage",
 data() {},
 methods: {
   exportExcel() {
      getReportExport(this.searchForm).then(res=>{});
    }
 }
}

截图
截图

posted @   张占岭  阅读(1762)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2018-07-16 知其所以然~tcp和udp的区别
2018-07-16 知其所以然~mongodb副本集
2018-07-16 知其所以然~分布式事务cap
2018-07-16 区块链扫盲
2014-07-16 ApacheBench~网站性能测试工具
2013-07-16 知方可补不足~SQL2008中的发布与订阅模式
2012-07-16 基础才是重中之重~委托实例的几种定义方式(规规矩矩method,逻辑简单delegate,层次清晰lambda
点击右上角即可分享
微信分享提示