1 根据文件路径下载文件模板,前端拿到的是stream 文件流
2 将文件流下载下来
- 第一步 当然是写请求方法了,如下
//下载模板
export function download (params) {
return request({
url:'/file/s3/file/xxxxxx.doc',//你懂的
method:'get',
responseType: 'blob',//重点 重点 重点
params
})
}
//记得在axios相应拦截器中 返回相应的blob
// 判断是否为文件流
if (response?.headers?.['content-type'] === 'application/octet-stream') {
return response.data
}
- 下一步当然是发送请求了
download().then((result) => {
//type 的配置对于我 可有可无,写上为了记录下
const blob = new Blob([result],{ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=UTF-8' })
this.downloadFile('xxxxx.doc',blob);
}).catch((err) => {
console.log(err);
});
因为使用的vue,所以有个全局配置
// 下载
Vue.prototype.downloadFile = (fileName, blob) => {
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 对象
URL.revokeObjectURL(eLink.href)
document.body.removeChild(eLink)
} else {
// IE10+下载
navigator.msSaveBlob(blob, fileName)
}
}