淺談vue中文件下載的幾種方式及方法封裝
更新時(shí)間:2023年01月13日 09:58:13 作者:嘖嘖靜
本文主要介紹了淺談vue中文件下載的幾種方式及方法封裝,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
一、通過對后端發(fā)送post請求,使用blob下載文件
/**
?* @param {blob} res - 導(dǎo)出數(shù)據(jù)
?* @param {string} fileName - 文件導(dǎo)出名稱
?* @param {string} format - 導(dǎo)出文件格式
?* @return {*}
?*/
function downBlob(res, fileName = "導(dǎo)出報(bào)表", format = "xlsx") {
? // 調(diào)用接口獲取到文件
? const blob = new Blob([res], {
? ? type: "application/vnd.ms-excel"
? });
? // 下載文件名
? fileName = fileName + parseInt(Math.random() * 9999) + "." + format;
? const linkNode = document.createElement("a");
? linkNode.download = fileName; // a標(biāo)簽的download屬性規(guī)定下載文件的名稱
? linkNode.style.display = "none";
? linkNode.href = URL.createObjectURL(blob); // 生成一個Blob URL
? document.body.appendChild(linkNode);
? linkNode.click(); // 模擬在按鈕上的一次鼠標(biāo)單擊
? URL.revokeObjectURL(linkNode.href); // 釋放URL 對象
? document.body.removeChild(linkNode);
}二、通過對后端發(fā)送post請求,使用url下載文件
/**
?* @param {string} fileName - 文件導(dǎo)出名稱
?* @param {string} url - 文件url地址
?* @return {*}
?*/
function download(fileName, url) {
? fileName = fileName || "導(dǎo)出報(bào)表";
? let arr = url.split(".");
? fileName += parseInt(Math.random() * 9999) + "." + arr[arr.length - 1];
? const linkNode = document.createElement("a");
? linkNode.download = fileName; // a標(biāo)簽的download屬性規(guī)定下載文件的名稱
? linkNode.style.display = "none";
? if (process.env.VUE_APP_TEM_PATH) {
? ? // 生成一個Blob URL
? ? linkNode.href = process.env.VUE_APP_TEM_PATH + url;
? } else {
? ? // 生成一個Blob URL
? ? linkNode.href = url;
? }
? document.body.appendChild(linkNode);
? linkNode.click(); // 模擬在按鈕上的一次鼠標(biāo)單擊
? URL.revokeObjectURL(linkNode.href); // 釋放URL 對象
? document.body.removeChild(linkNode);
}進(jìn)行main.js中全局引用
// 通過url下載文件
import { download } from "@/utils/auth";
Vue.prototype.$download = download;
// 通過blob下載文件
import { downBlob } from "@/utils/auth";
Vue.prototype.$downBlob = downBlob;實(shí)際使用方式
// res.data.url 通過url下載文件
this.$download("銷售統(tǒng)計(jì)", res.data.url);
// res 通過blob下載文件
this.$downBlob(res, "商城訂單與ERP訂單對照明細(xì)");到此這篇關(guān)于淺談vue中文件下載的幾種方式及方法封裝的文章就介紹到這了,更多相關(guān)vue 文件下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue-admin和后端(flask)分離結(jié)合的例子
本篇文章主要介紹了詳解vue-admin和后端(flask)分離結(jié)合的例子,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
在vue項(xiàng)目中集成graphql(vue-ApolloClient)
這篇文章主要介紹了在vue項(xiàng)目中集成graphql(vue-ApolloClient),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09
vue-better-scroll 的使用實(shí)例代碼詳解
這篇文章主要介紹了vue-better-scroll 的使用實(shí)例代碼詳解,代碼簡單易懂,非常不錯,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-12-12
swiper/vue 獲取 swiper實(shí)例方法詳解
在網(wǎng)上搜了一下如何調(diào)用swiper實(shí)例,大部分都是通過 swiperRef = new Swiper(‘.swiper’, options) 這種方法初始化swiper,然后直接能用 swiperRef 實(shí)例,這篇文章主要介紹了swiper/vue 獲取 swiper實(shí)例方法詳解,需要的朋友可以參考下2023-12-12

