若依下载文件(自带)

// 方法
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();
  })
}

// 导入
import { download } from '@/utils/request'
Vue.prototype.download = download

// 使用
 this.download(
        "/user/exportData", // 后端下载路径
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );

若依下载文件

// data: 接口返回的二进制流数据
// fileName:自定义下载完成后的文件名
// fileType:要下载的文件类型
export function downloadFile(data, fileName, fileType) {
    let blob = new Blob([data], { type: `${fileType};charset=utf-8` });// type指定下载文件的类型
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    downloadElement.download = fileName;
    document.body.appendChild(downloadElement);
    downloadElement.click();
    document.body.removeChild(downloadElement);
    window.URL.revokeObjectURL(href);
}


// 导入
import * as globalFun from "@/global/globalFun.js"
Vue.prototype.globalFun = globalFun

// 后端接口
export function export(){
    return request({
        url:  `/file/exportExcel`,
        method: 'get',
        responseType: "blob",
    })
}

// 使用
import * as Api from "@/api/download.js";
Api.export().then((res) => {
        // 文件名称
        const filename = `kqStatistics_${new Date().getTime()}.xlsx`;
        // 文件类型
        const fileType = "application/vnd.ms-excel";
        this.globalFun.downloadFile(res, filename, fileType);
        this.$modal.msgSuccess("导出成功");
      });