前端下载文件的几种方式 使用Blob下载文件

在前端下载文件是个很通用的需求,一般后端会提供下载的方式有两种:

1.直接返回文件的网络地址(一般用在静态文件上,比如图片以及各种音视频资源等)
2.返回文件流(一般用在动态文件上,比如根据前端选择,导出不同的统计结果 excel 等)

第一种方式比较简单,但是使用场景有限。
第二种方式通用性更好

我们先一下第一种的使用场景:

– a链接

<a href="https://www.baidu.top.pdf">下载文件</a>

我们可以通过download属性,可以实现对下载的文件进行重命名。

<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>

亿点小知识:在使用window.open的时候在除Google Chrome 浏览器会拦截内容但在其他浏览器是可以直接下载的

  • 如果要想Google Chrome 设置里面更改

第二种 使用blob文件流下载

<script>function Download() {axios({url: "www.baidu.pdf",method: 'GET',responseType: 'blob', // 这里就是转化为blob文件流headers: {token: 'sss' // 可以携带token}}).then(res => {const href = URL.createObjectURL(res.data)const box = document.createElement('a')box.download = '附件.pdf'box.href = hrefbox.click()})}</script>

下面封装了一个 blob的方法逻辑 感兴趣的可以参考一下

 // 下载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) // 创建下载的链接downloadElement.href = hrefdownloadElement.download = fileName // 下载后文件名document.body.appendChild(downloadElement)downloadElement.click() // 点击下载document.body.removeChild(downloadElement) // 下载完成移除元素window.URL.revokeObjectURL(href) // 释放掉blob对象}

以上就是前端下载文件的几种方式的属性和用法感谢大家的阅读
如碰到其他的问题 可以私下我 一起探讨学习
如果对你有所帮助还请点赞 收藏谢谢~!
关注收藏博客 作者会持续更新…