vue~使用axios實現excel文件下載的實現

前端VUE頁面上的導出或者下載功能,通常是調用後端的一個接口,由接口生成excel,word這些文件的流信息,返回給vue,而後由vue去構建下載的動做,這邊整理了一下,封裝了一下,方便之後複用。前端

封裝一個download文件

使用年月日時分秒毫秒作爲文件的名稱,下載爲excel文件vue

/**
 * 下載文件
 */
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=>{});
    }
 }
}

截圖
截圖ios

相關文章
相關標籤/搜索