vue实现文件下载功能

对接口进行请求:

//导出excel表到桌面
getData.exportexcel = (data)=>{ 
  return http({
    method: 'post',
    url: baseUrl + '/exportexcel/',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    },
    responseType: 'blob'
  })
}

对请求回来的数据进行方法下载和调用:

      exportexcel(){
        //打印报表
        url.exportexcel().then(res=>{
          console.log(res,this,'----------数据')
          this.download(res)
        })
        console.log('---------点击按钮')
      },
      download (data) {
          if (!data) {
              return
          }
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.id='Adownload'
          link.setAttribute('download', 'excel.xls') //命名可能会出现问题,格式一定和后端下载的格式一样
          
          document.body.appendChild(link)
          link.click()
          document.getElementById('Adownload').remove();
      }

点击下载按钮进行下载操作

<div @click="exportexcel">左侧屏幕</div>

 

posted @ 2020-11-30 15:41  嗯哼Nymph  阅读(5351)  评论(0编辑  收藏  举报