vue中带 token 的文件下载

1,133 阅读1分钟

使用 blob, axios, download.js 进行的文件下载

axios 请求

export function exportPlayProduct(params) {
  return request({
    url: "/lms/lmsPlayPlanProductInfo/exportExcel",
    method: "get",
    params: params,
    responseType: 'blob'
  });
}

responseType: 'blob' 必须增加的请求头。

响应数据处理

  1. 如果在统一响应数据中处理,(与后台协商),将数据返回到 promise 中
 const res = response.data
   if (response.status === 200 && !res.code) {
     // console.log(response)
     return response.data
   }

2. 接收响应数据

 // download
     const { id, playPlanName } = this.currentRow;
     const playload = {
       playPlanId: id,
     };
     exportPlayProduct(playload).then((res) => {
       // download(new Blob([res], {
       //   "type": "application/ms-excel"
       // }), `${playPlanName}.xls`);
       const blob = new Blob([res], {
         type: "application/vnd.ms-excel",
       });
       // let objectUrl = URL.createObjectURL(blob);
       // console.log(objectUrl, blob)
       download(blob, `${playPlanName}.xls`);
       //  window.location.href = objectUrl;
       // console.log(res)
     });

下载成功!!