前端vue中文件下載的三種方式匯總
前端vue中文件下載的三種方式
第一種方式是前端創(chuàng)建超鏈接,通過a標簽的鏈接向后端服務(wù)發(fā)get請求,接收后端的文件流,非常簡單:
<a :href='"/user/downloadExcel"' >下載模板</a>
另一種情況是創(chuàng)建div標簽,動態(tài)創(chuàng)建a標簽:
<div name="downloadfile" onclick="downloadExcel()">下載</div>
function downloadExcel() {
let a = document.createElement('a')
a.href ="/user/downloadExcel"
a.click();
}
還有一種補充:
function downloadExcel() {
window.location.href = "/tUserHyRights/downloadUsersUrl";
}
第二種方式通過創(chuàng)建iframe的方式:
<el-button size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport(scope.row)">導出</el-button>
//method方法:
handleExport(row) {
var elemIF = document.createElement('iframe')
elemIF.src = 'user/downloadExcel?snapshotTime=' + formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm') +
'&category=' + row.category
elemIF.style.display = 'none'
document.body.appendChild(elemIF)
}
第三種方式,會對后端發(fā)的post請求,使用blob格式
<el-button size="mini" class="filter-item" type="primary" icon="el-icon-download" @click="handleExport(scope.row)">導出</el-button>
//method方法
handleExport(row){
const url="/user/downloadExcel"
const options = {snapshotTime:formatDate(new Date(row.snapshotTime), 'yyyy-MM-dd hh:mm')}
exportExcel(url,options)
}
/**
* 封裝導出Excal文件請求
* @param url
* @param data
* @returns {Promise}
*/
//api.js
export function exportExcel(url, options = {}) {
return new Promise((resolve, reject) => {
console.log(`${url} 請求數(shù)據(jù),參數(shù)=>`, JSON.stringify(options))
axios.defaults.headers['content-type'] = 'application/json;charset=UTF-8'
axios({
method: 'post',
url: url, // 請求地址
data: options, // 參數(shù)
responseType: 'blob' // 表明返回服務(wù)器返回的數(shù)據(jù)類型
}).then(
response => {
resolve(response.data)
let blob = new Blob([response.data], {
type: 'application/vnd.ms-excel'
})
console.log(blob)
let fileName = Date.parse(new Date()) + '.xlsx'
if (window.navigator.msSaveOrOpenBlob) {
// console.log(2)
navigator.msSaveBlob(blob, fileName)
} else {
// console.log(3)
var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = fileName
link.click()
//釋放內(nèi)存
window.URL.revokeObjectURL(link.href)
}
},
err => {
reject(err)
}
)
})
}
如果后端提供的下載接口是get類型,可以直接使用方法一和二,簡單又便捷;當然如果想使用方法三也是可以的,不過感覺有點舍近求遠了。
如果后端提供的下載接口是post類型,就必須要用方法三了。
附:vue實現(xiàn)圖片或文件下載功能實例
要自己創(chuàng)建一個a標簽,以下就是下載功能的實現(xiàn)
這里是調(diào)用接口之后如果code=200時進行下載
if (res.code == 200) {
const link = document.createElement("a"); //自己創(chuàng)建的a標簽
link.href = res.data;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(res.data);
}
2、還有一種情況是下載單張圖片,如果用上面方法會直接跳轉(zhuǎn)到了圖片鏈接,并不會實現(xiàn)下載。下面則是下載單張圖片的方法
getUrlBase64(imgUrl) {
return new Promise((resolve) => {
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
let img = new Image(); //允許進行跨域
img.crossOrigin = "Anonymous";
img.src = imgUrl;
img.onload = function() {
canvas.height = img.height; //圖片的高度
canvas.width = img.width;//圖片的寬度
ctx.drawImage(img, 0, 0, img.width, img.height);
let dataURL = canvas.toDataURL("image/png");
canvas = null;
resolve(dataURL);
};
});
},
//點擊下載圖片按鈕的事件
handleDowondImg(url, name) {
this.getUrlBase64(url).then((base64) => {
const link = document.createElement("a");
link.href = base64;
link.download = this.$route.query.source;
link.click();
});
},
總結(jié)
到此這篇關(guān)于前端vue中文件下載的三種方式的文章就介紹到這了,更多相關(guān)vue中文件下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用vuex緩存數(shù)據(jù)并優(yōu)化自己的vuex-cache
這篇文章主要介紹了使用vuex緩存數(shù)據(jù)并優(yōu)化自己的vuex-cache,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
element-plus按需引入后ElMessage與ElLoading在頁面中的使用
這篇文章主要介紹了element-plus按需引入后ElMessage與ElLoading在頁面中的使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09
vue3中keep-alive和vue-router的結(jié)合使用方式
這篇文章主要介紹了vue3中keep-alive和vue-router的結(jié)合使用方式,?具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10
在nuxt使用vueX代替storage的實現(xiàn)方案
這篇文章主要介紹了在nuxt使用vueX代替storage的實現(xiàn)方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10

