1. 程式人生 > 實用技巧 >vue實現檔案下載功能

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>