Vue element-admin 中使用文件下载
前言
最近接到一个需求,要在后台管理系统下载一个 zip
,但是这个 zip
文件是由接口生成并返回给前端的,接口返回的 content-type
是 application/zip
,但这个时候前端是需要做特殊处理把接口返回的文件流下载下来的。
实现
1. 请求接口
在请求接口是需要指定 responseTyp
e 为 blob
,否则下载下来的文件会无法解压。
export function downloadKeyFile(param) {
return request({
url: '/terminal/downloadKeyFile',
method: 'post',
data: param,
responseType: 'blob' // 表明返回服务器返回的数据类型
})
}
2. 拦截响应
由于使用了统一的接口设置,所有返回的数据都会在 request.js
中进行提前的过滤和筛选,所以需要在 request.js
中进行拦截接口返回的 content-type
为 application/zip
的响应,拦截后执行下载到用户本地 zip
包的逻辑,下面直接贴具体代码:
const res = response.data
const respContentType = response.headers['content-type']
// 如果响应类型是 zip 包,则执行下载文件逻辑
if (respContentType === 'application/zip') {
if (!res) {
return
}
const url = window.URL.createObjectURL(new Blob([res], {
type: 'application/zip'
}))
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', 'appIconZip.zip')
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
return
}
参考文章
vue element admin 中使用文件下载
vue 文件下载(需调用接口)
PHP 使用 ZipArchive 打包 zip
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: