当后台以文件流形式的返回Excal的时候处理


以下未axios,vue导出后台文件流形式Excel

 

 

这次的需求是导出excel表格,但不是给你返回网络路径。而是以文件流的形式返回一串乱码的玩意儿。看不懂。
以前没接触过这种东西,只是听说过后台可以文件流返回而今天一看却是懵逼的状态。
项目使用vue+axios 和element ui
使用post请求做到自下载。

下文代码

```
exportData () {
  const form = this.getSearchForm() // 要发送到后台的数据
  axios({ // 用axios发送post请求
  method: 'post',
  url: '/user/12345', // 请求地址
  data: form, // 参数
  responseType: 'blob' // 表明返回服务器返回的数据类型
})
.then((res) => { // 处理返回的文件流
  const content = res
  const blob = new Blob([content])
  const fileName = '测试表格123.xls'
  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) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
})
}
```
// 一定要看到 responType:'blob'

```
axios.post(url,data,{responseType:'blob'}) 这样死活就是不行
```

```
axios({
method: 'post',
url: '/user/12345', // 请求地址
data: form, // 参数
responseType: 'blob' // 表明返回服务器返回的数据类型
})
.then((response)=>{
  const blob = new Blob([response])
  const fileName = '测试表格123.xls'
  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) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
})

 

```


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM