前端下載文件的幾種方式 使用Blob下載文件
在前端下載文件是個(gè)很通用的需求,一般后端會(huì)提供下載的方式有兩種:
1.直接返回文件的網(wǎng)絡(luò)地址(一般用在靜態(tài)文件上,比如圖片以及各種音視頻資源等)
2.返回文件流(一般用在動(dòng)態(tài)文件上,比如根據(jù)前端選擇,導(dǎo)出不同的統(tǒng)計(jì)結(jié)果 excel 等)
第一種方式比較簡單,但是使用場景有限。
第二種方式通用性更好
我們先一下第一種的使用場景:
- a鏈接
<a href="https://www.baidu.top.pdf">下載文件</a>
我們可以通過download屬性,可以實(shí)現(xiàn)對下載的文件進(jìn)行重命名。
<a href="https://www.baidu.top.pdf" download="附件.pdf">下載文件</a>
- 還可以使用編程式的寫法:
1.location的href
<script>
function Download() {
window.location.href = 'www.baidu.pdf'
}
</script>
2.window.open
<script>
function Download() {
window.open('www.baidu.pdf')
}
</script>
億點(diǎn)小知識(shí):
在使用window.open的時(shí)候在除Google Chrome 瀏覽器會(huì)攔截內(nèi)容但在其他瀏覽器是可以直接下載的
- 如果要想Google Chrome 設(shè)置里面更改
第二種 使用blob文件流下載
<script>
function Download() {
axios({
url: "www.baidu.pdf",
method: 'GET',
responseType: 'blob', // 這里就是轉(zhuǎn)化為blob文件流
headers: {
token: 'sss' // 可以攜帶token
}
}).then(res => {
const href = URL.createObjectURL(res.data)
const box = document.createElement('a')
box.download = '附件.pdf'
box.href = href
box.click()
})
}
</script>
下面封裝了一個(gè) blob的方法邏輯 感興趣的可以參考一下文章來源:http://www.zghlxwxcb.cn/news/detail-469274.html
// 下載
const DownloadFile = (row: any) => {
contractApi
.xxxApi({ fullFileName: row.filePath })
.then((blob: any) => {
row.fileFormat = row.filePath.split('.')[row.filePath.split('.').length - 1]
download(blob, row.fileFormat, row.fileName)
})
}
export function download(file: any, fileType: string, fileName?: string) {
const blob = new Blob([file], { fileType})
const downloadElement = document.createElement('a')
const href = window.URL.createObjectURL(blob) // 創(chuàng)建下載的鏈接
downloadElement.href = href
downloadElement.download = fileName // 下載后文件名
document.body.appendChild(downloadElement)
downloadElement.click() // 點(diǎn)擊下載
document.body.removeChild(downloadElement) // 下載完成移除元素
window.URL.revokeObjectURL(href) // 釋放掉blob對象
}
以上就是前端下載文件的幾種方式
的屬性和用法感謝大家的閱讀
如碰到其他的問題 可以私下我 一起探討學(xué)習(xí)
如果對你有所幫助還請點(diǎn)贊
收藏謝謝~!
關(guān)注收藏博客 作者會(huì)持續(xù)更新…文章來源地址http://www.zghlxwxcb.cn/news/detail-469274.html
到了這里,關(guān)于前端下載文件(Blob)的幾種方式使用Blob下載文件的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!