momo's Blog.

使用axios下载后端数据流

字数统计: 312阅读时长: 1 min
2021/09/03 Share

前言

前后端交互过程中,难免会出现文件下载的功能, 那么我们如果通过axios去下载文件呢?

后端

后端我们采用的是Python, 实际代码如下

1
2
3
4
f = ftp.open(path)
response = FileResponse(f)
response['Content-Disposition'] = f'attachment;filename="{path.split("/")[-1]}"'
return response

前端

axios 配置

1
2
3
4
5
6
7
8
9
export function getFile(id, path) {
return request({
url: '/api/file/object/',
method: 'get',
params: { id: id, path: path },
responseType: 'blob',
timeout: 1000000000
})
}
  • 核心代码
1
2
3
4
5
6
7
8
9
10
11
12
handleDownload(fileName) {
const path = this.path + '/' + fileName
getFile(this.id, path).then(response => {
const url = window.URL.createObjectURL(new Blob([response]))
const link = document.createElement('a')
link.href = url
link.setAttribute('download', fileName) // or any other extension
document.body.appendChild(link)
link.click()
link.remove()
})
}

思考

使用此方法下载的时候, 文件进度是无法显示的, 只会在所有进度下载完成以后才会保存.

并且在下载的过程中, 文件的内容是率先保存在内存当中, 如果是大文件则无法使用.

总结下来, 尽量不要使用xhr去下载大文件, 如果要下载大文件则推荐使用浏览器

1
windows.open(url)

但是使用浏览器的功能, 去下载一些需要鉴权的文件就需要额外的判断.

参考文档

CATALOG
  1. 1. 前言
  2. 2. 后端
  3. 3. 前端
    1. 3.1. axios 配置
  4. 4. 思考
  5. 5. 参考文档