Vue-element-admin获取ThinkPHP5 传输过来的excel数据流的发方法

api接口请求中添加responseType: 'arraybuffer',

export function exportData(data) {
  return request({
    url: '/crawler/taskmanagement/exportexcel',
    responseType: 'arraybuffer',
    method: 'post',
    data
  })
}

接受后端穿过来的数据流方法一:

      DownloadData(id) {
        var that = this
        exportData({id: id}).then(res => {
          let blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
          let objectUrl = URL.createObjectURL(blob);
          window.location.href = objectUrl;
        })
      },

接受后端穿过来的数据流方法二(此方法可以指定下载表格的名称):

      DownloadData(id) {
        var that = this
        exportData({id: id}).then(res => {
          const filename = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]) || '分拣表.xlsx' // 获取后端返回存在请求头里边的表单名字
          that.$options.methods.fileDownload(res.data, filename);
        })
      },

 fileDownload(data, fileName) {
        const blob = new Blob([data], {
          type: 'application/octet-stream'
        })
        const filename = fileName || 'filename.xls'
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(blob, filename)
        } else {
          var blobURL = window.URL.createObjectURL(blob)
          var tempLink = document.createElement('a')
          tempLink.style.display = 'none'
          tempLink.href = blobURL
          tempLink.setAttribute('download', filename)
          if (typeof tempLink.download === 'undefined') {
            tempLink.setAttribute('target', '_blank')
          }
          document.body.appendChild(tempLink)
          tempLink.click()
          document.body.removeChild(tempLink)
          window.URL.revokeObjectURL(blobURL)
        }
      },

后端使用ThinkPHP5,后端相关编码请查看https://blog.csdn.net/supramolecular/article/details/83303944

猜你喜欢

转载自blog.csdn.net/supramolecular/article/details/83349008