vue axios 下載文件

功能:點擊導出按鈕,提交請求,下載excel文件;

第一步:跟後端童鞋確認交付的接口的response header設置了

response header

以及返回了文件流。

第二步:修改axios請求的responseType爲blob,以post請求爲例:

      this.$post({
        method: 'post',
        url: 'api/user/',
        data: {
          firstName: 'Fred',
          lastName: 'Flintstone'
        },
        responseType: 'blob'
      })
        .then(response => {
          this.download(response)
        })
        .catch(error => {})

第三步:請求成功,拿到response後,調用download函數(創建a標籤,設置download屬性,插入到文檔中並click)

    // 下載文件
    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.setAttribute('download', 'excel.xlsx')

      document.body.appendChild(link)
      link.click()
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章