vue中如何下載文件導出保存到本地
vue下載文件導出保存到本地
先分析如何下載:先有一個鏈接地址,然后使用 location.href或window.open()下載到本地
看看返回數(shù)據(jù)

res.config.url 中是下載鏈接地址,res.data 中是返回的二進制數(shù)據(jù)
如何下載
...
<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
這樣就能實現(xiàn)在當前窗口下載文件了
另一種情況
如果下載的文件既可以是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)
})
vue中a標簽下載本地文件-未找到,原因及解決
錯誤代碼
在vue項目中下載本地圖片資源時失敗并顯示未找到,項目中代碼為:
<a href="../../assets/bg.png" download="bg"> ? <img src="../../assets/bg.png"></img> </a>
原因
執(zhí)行npm run serve 之后,在瀏覽器的調(diào)試工具下看a標簽和img標簽的代碼為:
<a href="../../assets/bg.png" download="bg"> ? <img src="/img/bg.png"></img> </a>
會把圖片資源放入/img文件下,也就是說上面的bg.png的在項目運行后真實路徑為http://localhost:8080/img/bg.jpg,故a標簽的href有誤,提示找不到文件,下載失敗。
需要注意的是,如果圖片大小小于4k,會直接把文件轉為為base64文件,并放入css文件中,不會像上述圖片一樣,解析后放入/img下面。
解決
在href里面寫npm run serve命令運行后的圖片路徑:
<a href="/img/bg.png" download="bg"> ? <img src="../../assets/bg.png"></img>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
vue-cli創(chuàng)建項目ERROR?in?Conflict:?Multiple?assets?emit?dif
最近vue/cli創(chuàng)建項目后出現(xiàn)了錯誤,下面這篇文章主要給大家介紹了關于vue-cli創(chuàng)建項目ERROR?in?Conflict:?Multiple?assets?emit?different?content?to?the?same?filename?index.html問題的解決辦法,需要的朋友可以參考下2023-02-02
Vue使用el-input自動獲取焦點和二次獲取焦點問題及解決
這篇文章主要介紹了Vue使用el-input自動獲取焦點和二次獲取焦點問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12

