vue中下载文件导出保存到本地
vue中下載文件導(dǎo)出保存到本地
先分析如何下載:先有一個鏈接地址,然后使用 location.href或window.open()下載到本地
看看返回數(shù)據(jù)
?
res.config.url 中是下載鏈接地址,res.data 中是返回的二進(jìn)制數(shù)據(jù)
如何下載
...
<el-button icon="el-icon-download" @click="download(id)"></el-button>
...
download(id) { // 導(dǎo)出
? 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
這樣就能實現(xiàn)在當(dāng)前窗口下載文件了
另一種情況
如果下載的文件既可以是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 打印出來看里面包含的內(nèi)容
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)
})
?
總結(jié)
以上是生活随笔為你收集整理的vue中下载文件导出保存到本地的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java开发平板_用Android平板来
- 下一篇: html5倒计时秒杀怎么做,vue 设