vue 導出文件,攜帶請求頭token

前言

本文並不能直接複製到本地看效果,僅提供代碼參考

1.使用axios的方式攜帶請求頭token
在這裏插入圖片描述
2.設置響應的數據類型

responseType: "blob"

3.請求成功,返回二進制文件的數據回來
在這裏插入圖片描述
4.請求失敗,返回json
在這裏插入圖片描述
5.示例代碼

<template>
  <div>
    <el-button type="primary" size="small" :loading="btnLoading" @click="exportFile">導出</el-button>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      btnLoading: false
    };
  },
  methods: {
    // responseType 響應類型
    exportFile() {
      this.btnLoading = true;
      axios({
        method: 'get',
        url: '/api',
        headers: {
          token: '79faf82271944fe38c4f1d99be71bc9c'
        },
        responseType: "blob"
      })
        .then(res => {
          this.btnLoading = false;
          if (res.data.type) {
            // 文件下載
            const blob = new Blob([res.data], {
              type: "application/vnd.ms-excel"
            });
            let link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', '導出文件.xlsx');
            link.click();
            link = null;
            this.$message.success('導出成功');
          } else {
            // 返回json
            this.$message.warning(res.data.msg);
          }
        })
        .catch(err => {
          this.btnLoading = false;
          this.$message.error("下載失敗");
        });
    }
  }
};
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章