egg.js 下载导出服务端生成的文件

3,250 阅读1分钟
    //前端请求
    axios({
      method: 'post',
      url: '/api/cba/export-excel',
      data: this.state.selectRowRecord,
      responseType: 'blob',
    }).then((res) => {
      if (res.status === 200) {
        console.log(res)
        if(res) {
          let url = window.URL.createObjectURL(res.data);
          let link = document.createElement('a');
          link.style.display = 'none';
          link.href = url
          link.setAttribute('download', `${moment(new Date()).format('YYYY-MM-DD')}.xlsx`);
          document.body.appendChild(link);
          link.click()
        }
      }
    });
    
    //服务端处理
    async download() {
        const filePath = path.resolve(this.app.config.static.dir, 'test.xlsx');
        this.ctx.attachment('test.xlsx');
        this.ctx.set('Content-Type', 'application/octet-stream');
        this.ctx.body = fs.createReadStream(filePath);
    }

以上代码在chrome中运行良好。但在safari-12版本中会出现导出时blob:http://xxxxxxx 原因是safari不支持blob下载。

其他方式

使用fileSaver.js 做兼容
https://github.com/eligrey/FileSaver.js/#supported-browsers