日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > vue >内容正文

vue

vue中下载文件导出保存到本地

發(fā)布時間:2023/12/8 vue 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 vue中下载文件导出保存到本地 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。