js 匯出檔案流

everseven發表於2024-08-17
export function downLoad (res, name, type) { // 封裝方法
  let resfileName = decodeURI(res.headers['content-disposition'].split('=')[1]) // 取後臺命名
  let fileName = ''
  if (resfileName && resfileName !== 'null' && resfileName !== '' && resfileName.length) {
    fileName = resfileName
  } else { // 後端未命名處理
    fileName = (name || '-') + parseTime(new Date(), '{y}-{m}-{d}') + '.xls'
  }
  if (type) { fileName = name }
  const blob = new Blob([res.data], {})
  if ('download' in document.createElement('a')) {
    // 非IE下載
    const elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href)
    document.body.removeChild(elink)
  } else {
    // IE10+下載
    navigator.msSaveBlob(blob, fileName)
  }
}

 

handleExport (obj) { // 匯出介面呼叫
    return request({
      url: '/api/export',
      method: 'get',
      params: obj,
      responseType: 'blob' // 重點!
    })
  }

  

參考連結

相關文章