vue中下载文件导出保存到本地
vue中下载文件导出保存到本地先分析如何下载:先有一个链接地址,然后使用 location.href或window.open()下载到本地看看返回数据res.config.url 中是下载链接地址,res.data 中是返回的二进制数据如何下载...<el-button icon="el-icon-download" @click="download(id)"></el-butt
·
vue中下载文件导出保存到本地
先分析如何下载:先有一个链接地址,然后使用 location.href
或window.open()
下载到本地
看看返回数据
res.config.url
中是下载链接地址,res.data
中是返回的二进制数据
如何下载
...
<el-button icon="el-icon-download" @click="download(id)"></el-button>
...
download(id) { // 导出
this.$API({
name: 'Download',
paths: [id]
}).then(res => {
// window.open(res.config.url, '_self')或者
window.location.href = res.config.url
}).catch(error => {
this.$message({ type: 'error', message: error })
}).finally(() => {
})
}
上面情况针对的是后端返回文件流,如果后端返回的是文件名
通用下载方法
window.location.href = baseURL + "/common/download?fileName=" + encodeURI(fileName) + "&delete=" + true
这样就能实现在当前窗口下载文件了
另一种情况
如果下载的文件既可以是txt文件或html文件也可以是压缩包等,对于这种类型的下载处理
download (row) { // 下载
this.$API({
name: 'DownloadResource',
params: {
path: row.path,
token: this.$Cookies.get('token')
},
headers: {
'Content-Type': 'application/octet-stream'
},
requireAuth: true
}).then (res => {
window.open(`${res.config.url}?path=${res.config.params.path}&token=${res.config.params.token}`, '_self')
}).catch(error => {
this.$message.error(error)
})
}
对于 headers
中的 'Content-Type': 'application/octet-stream'
,需要在 axios 拦截器中单独处理
建议把 res 打印出来看里面包含的内容
axios.interceptors.response.use(res => {
// 处理下载文件的接口
if (res.config.headers['Content-Type'] === 'application/octet-stream') {
return res
}
if (res.data.code) {
return Promise.resolve(res)
} else {
return Promise.reject(res)
}
}, error => {
return Promise.reject(error)
})
根据接口返回的url下载pdf文件
pdf的URL直接打开的话是网页预览界面,而不是文件下载,文件下载需要的是二进制数据,但是如果接口返回的是在线链接,那么可以通过以下操作进行格式转化再去下载
import axios from 'axios';
methods: {
async downloadPDF(pdfUrl) {
const response = await axios({
url: pdfUrl,
method: 'GET',
responseType: 'blob', // 必须指定为blob类型才能下载
});
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', this.doFormatFileName(pdfUrl));
document.body.appendChild(link);
link.click();
},
},
doFormatFileName(name) {
if (name) {
return name?.split('\/')?.at(-1);
}
return name;
},
更多推荐
已为社区贡献31条内容
所有评论(0)