您好,登錄后才能下訂單哦!
這篇文章主要介紹了前端vue中怎么實(shí)現(xiàn)文件下載的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇前端vue中怎么實(shí)現(xiàn)文件下載文章都會有所收獲,下面我們一起來看看吧。
前端創(chuàng)建超鏈接,通過a標(biāo)簽向后端發(fā)送get請求,需要給a標(biāo)簽添加一個(gè)download屬性
這種寫法是創(chuàng)造了一個(gè)a標(biāo)簽,把地址寫到a標(biāo)簽里再用js調(diào)用點(diǎn)擊,實(shí)現(xiàn)訪問文件地址就是下載了
代碼如下:
<a @click="downloadFile(file.url,file.originalFilename, file.id, file.fileTye)" >下載</a> // 參數(shù)分別是:文件的路徑 文件的名字 文件的id 文件的類型
downloadFile(url, fileName, flieId, type) { let link = document.createElement('a'); link.style.display = 'none'; link.href = baseUrl + '/xxx/xxx/xxx?flieId=' + flieId; document.body.appendChild(link); link.click(); },
或者
<a :href='"/user/downloadExcel"' >下載模板</a> //另一種情況是創(chuàng)建div標(biāo)簽,動(dòng)態(tài)創(chuàng)建a標(biāo)簽: <div name="downloadfile" "downloadExcel()">下載</div> function downloadExcel() { let a = document.createElement('a') a.href ="/xxx/xxx" a.click(); }
通過window.open()下載
window.open就是打開了一個(gè)新網(wǎng)頁直接在新網(wǎng)頁訪問文件地址了,只要訪問文件地址,就能下載文件。這時(shí)候后端返回的是文件流直接渲染,不需要url再打開下載了
downloadFile() { window.open( baseUrl + '/xxx/xxx/xxx/getTemplate?templateCode=manual_pc', '_self' ); },
通過創(chuàng)建iframe的方式:
<el-button size="mini" @click="handleExport(scope.row)">導(dǎo)出</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格式,這種寫法對于圖片和pdf及svg能實(shí)現(xiàn)下載功能
<a @click="downloadFile(file.name, file.url)" >下載</a> /* 第一個(gè)參數(shù)是文件的名字,第二個(gè)參數(shù)是文件的路徑*/ downloadFile(fileName, fileUrl) { if (!fileUrl) { return; } let url = window.URL.createObjectURL(new Blob([fileUrl])); let link = document.createElement('a'); link.style.display = 'none'; link.href = url; link.setAttribute('download', fileName); document.body.appendChild(link); link.click(); }
如果后端返回的格式是文件流形式的,就不用轉(zhuǎn)換成Blob形式了。就可以直接簡寫為:
<a :href="src" rel="external nofollow" download="name"/>
因?yàn)槭俏募飨螺d,所以在取后臺數(shù)據(jù)的時(shí)候,要多傳遞一個(gè)【responseType: ‘blob’】這個(gè)參數(shù)
function downloadPost (config){ return new Promise((resolve,reject) => { axios({ url: config.url,// 請求地址 method: 'post', data: config.data,// 參數(shù) responseType: 'blob'// 表明返回服務(wù)器返回的數(shù)據(jù)類型 }).then(res => { resolve(res) }).catch(err=>{ reject(err); }); }); }
如果后端提供的下載接口是get類型,可以直接使用方法一和二和三,簡單又便捷;當(dāng)然如果想使用方法四也是可以的,不過感覺有點(diǎn)舍近求遠(yuǎn)了。
如果后端提供的下載接口是post類型,就必須要用方法四了。
關(guān)于“前端vue中怎么實(shí)現(xiàn)文件下載”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“前端vue中怎么實(shí)現(xiàn)文件下載”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。