前端調用后端接口導出文件


情況1:

有遇到過只需要這樣就能成功調用的接口:

  const url = process.env.VUE_APP_BASE_API + '/api/export'
  window.location.href = url

情況2:

有時候要麻煩點:

api:

  export(params = {}) {
    return httpPost('/api/export', params, { responseType: 'blob' })
  }

 

組件:

// 導出數據
    exportData() {
      costModel.export({
        page: 1,
        pageSize: this.total,
        ...this.searchParams
      }).then(res => {
        console.log('res', res)
        const a = document.createElement('a')
        // 創鍵臨時url對象
        const url = URL.createObjectURL(res)

        a.href = url
        a.download = '表格.xlsx'
        a.click()
        // 釋放之前創建的URL對象
        window.URL.revokeObjectURL(url)
      })
    },

 可以封裝一下:

export function exportFile(blob, title, type = 'xlsx') {
  const a = document.createElement('a')
  // 創鍵臨時url對象
  const url = URL.createObjectURL(blob)
  a.href = url
  // 文件名
  a.download = title + '.' + type
  a.click()
  // 釋放之前創建的URL對象
  window.URL.revokeObjectURL(url)
}

組件中調用:

exportData() {
      costListModel.export({
        page: 1,
        pageSize: this.total,
        ...this.searchParams
      }).then(res => {
        // console.log('res', res)
        exportFile(res, '文件標題', 'xlsx')
      })
    },

 

知識點補充:

URL.createObjectURL()

參考:https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL

HTML <a> download 屬性

參考:https://www.runoob.com/tags/att-a-download.html

download 屬性是HTML5中新增的 <a> 標簽屬性。

<a download="filename">

filename: 指定文件名稱。

HTML對象 <a>

參考:https://www.w3school.com.cn/jsref/dom_obj_anchor.asp


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM