欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

前端處理axios請(qǐng)求下載后端返回的文件流代碼實(shí)例

 更新時(shí)間:2024年07月20日 14:53:53   作者:大力99  
使用axios可以很方便地獲取后端返回的文件流數(shù)據(jù),并在前端直接在瀏覽器下載,這篇文章主要給大家介紹了關(guān)于前端處理axios請(qǐng)求下載后端返回的文件流的相關(guān)資料,需要的朋友可以參考下

需求:

點(diǎn)擊按鈕下載文件,請(qǐng)求后端接口,后端返回文件流,如果遇到錯(cuò)誤信息并不能簡(jiǎn)單的res.message拿到錯(cuò)誤提示,而且想要正常下載前端也需要做些處理。

1.請(qǐng)求接口要加上響應(yīng)類型為blob, responseType: ‘blob’,如:

function logsDownload(params) {
 return axios.get('xxx/xxx/xxx',{
   params,
   responseType: 'blob'
 })
}

2.定義一個(gè)下載的方法

function download(fileName ='log', type: 'txt' | 'json, file:Blob) {
   const blob = new Blob([file]);
    // 獲取heads中的filename文件名
    const downloadElement = document.createElement('a');
    // 創(chuàng)建下載的鏈接
    const href = window.URL.createObjectURL(blob);
    downloadElement.href = href;
    // 下載后文件名
    downloadElement.download = `${fileName}.${type}`
    document.body.appendChild(downloadElement);
    // 點(diǎn)擊下載
    downloadElement.click();
    // 下載完成移除元素
    document.body.removeChild(downloadElement);
    // 釋放掉blob對(duì)象
    window.URL.revokeObjectURL(href);
}

3.借助FileReader對(duì)象實(shí)現(xiàn),F(xiàn)ileReader.readAsText(data)開(kāi)始讀取指定的Blob中的內(nèi)容。

result屬性中將包含一個(gè)字符串以表示所讀取的文件內(nèi)容。

讀取操作完成時(shí)觸發(fā)FileReader.onload(),在這里通過(guò)reader.result拿到讀取的文件內(nèi)容(即后端返回值),然后對(duì)其json序列化,即

可拿到后端返回的message,然后進(jìn)行相應(yīng)的展示即可。

// 定義一個(gè)讀取文件的方法
async function readFileAsText (file:File){
      const fileReader = new FileReader()
      let text
      await new Promise(resolve=>{
         fileReader.onLoad = ()=>{
            text = fileReader.result
            resolve(true)
         }
        fileReader.readAsText(file, 'utf8')
      })
      return text || ''
 }

4.請(qǐng)求成功和失敗的返回結(jié)果是不同

請(qǐng)求下載一個(gè)文件,請(qǐng)求成功時(shí)返回的是一個(gè)文件流,type是對(duì)應(yīng)文件類型,例如:text/xml,正常導(dǎo)出文件; 而請(qǐng)求失敗的時(shí)候返回的是json ,type為application/json,不會(huì)處理錯(cuò)誤信息,而是直接導(dǎo)出包含錯(cuò)誤信息的文件。

但是無(wú)論成功還是失敗,返回的結(jié)果都是blob格式的文件流。

因此可以通過(guò)返回的blob數(shù)據(jù)type類型進(jìn)行區(qū)分,如果type是文件類型,導(dǎo)出文件,如果type是json則把blob數(shù)據(jù)轉(zhuǎn)為string,處理錯(cuò)誤信息。

在響應(yīng)攔截器那里加入以下,需要判斷如果時(shí)文件流直接返回的情況

// 響應(yīng)攔截器
banseInstance.interceptors.response.use(response => {
  ...
  // 文件流直接返回
  if (response .request.responseType === 'blob' ) {
      if (response .data.type === 'application/json') {
        const res = await readFileAsText(response.data)

        ElMessage.error(JSON.parse(res).message || '下載失敗')
        return false;
     } else {
       return response .data;
     }
  }
 ...
}

點(diǎn)擊按鈕下載

  const handleDown = () => {
    const fileName = 'xxxx'
    const file = await logsDownload(params)
    if (file) {
     download(fileName, 'txt', file)
     ElMessage.success('下載成功')
    }
  }

總結(jié) 

到此這篇關(guān)于前端處理axios請(qǐng)求下載后端返回的文件流的文章就介紹到這了,更多相關(guān)axios請(qǐng)求下載后端返回文件流內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論