前言
由于跨域,所以无法直接通过window.location.href或者a标签直接下载,直接拼后台接口地址又暴露了后台地址,不可行。
所以在这种跨域情况下,本章讲一下vue如何下载后台接口提供的application/octet-stream文件流Excel文件。
功能
实现前端vue下载后台返回的application/octet-stream文件流
1、使用blob类型请求
2、获取到数据后处理成Blob数据
3、通过创建一个a标签,将Blob数据转换成base64数据,放到a标签的url中
4、触发a标签点击事件实现下载Blob数据
5、删除a标签
代码实现
/*** 导出excel* @param fileName* @returns {AxiosPromise}*/
export function exportExcel(fileName){request({url: '/xxx/getCameraXls?fileName='+fileName,method: 'get',responseType:'blob'}).then(res=>{const date = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '').replace(/\-/g, '').replace(/\:/g, '').replace(/\s*/g, '')const downloadName = fileName +'-'+ date + '.xlsx'downloadFunc(downloadName,res)})
}function downloadFunc(fileName,data){const blob = new Blob([data], { type: `'application/vnd.ms-excel';charset=utf-8` })const downloadElement = document.createElement('a')const href = window.URL.createObjectURL(blob)downloadElement.href = hrefdownloadElement.download = fileNamedocument.body.appendChild(downloadElement)downloadElement.click()document.body.removeChild(downloadElement)window.URL.revokeObjectURL(href)
}