小秦哥 发表于 2024-7-17 23:13:28

前端下载文件流(可暂停、取消、查看进度)

<el-button type="primary" icon="Download" plain @click="handleDownload('batch')">下载</el-button>
1、a标签下载(没有进度条,接口走完前端才有反应,下载大文件时用户体验不好,实用下载小文件)
// 下载
const handleDownload = async row => {
    if (selectedData.value && selectedData.value.length != 0) {
      selectedData.value.forEach(item=>{
      downloadFileAuthentication(item.propertyId).then(res => {
          downloadFileHref(item.propertyId).then(res => {
            const blob = new Blob(, { type: 'application/zip' })
            const link = document.createElement('a')//创建a标签
            link.download = item.propertyName//a标签添加属性
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            document.body.appendChild(link)
            link.click()//执行下载
            URL.revokeObjectURL(link.href) //释放url
            document.body.removeChild(link)//释放标签
          })
      })
      })
      
    } else {
      ElMessage.warning('请先选择操作数据');
    }
}
2、 window.location.href下载(有进度条,可取消、暂停。缺点:一次只能下载一条,不支持批量下载)(这里后端get哀求方式传参)
const handleDownload = async row => {
const url = `/ca/download/downloadFile?propertyId=${row.propertyId}`;
downloadFileAuthentication(row.propertyId).then(res => {
    if (res.code == 200) {
      window.location.href = ` ${downLoadUrl + url}&token=${getToken()}`
    }
})
};
3、iframe下载(有进度条,可取消、暂停,支持同时下载多个)
const handleDownload = async row => {
    if (selectedData.value && selectedData.value.length != 0) {
      selectedData.value.forEach(item=>{
      downloadFileAuthentication(item.propertyId).then(res => {
          downloadFileHref(item.propertyId).then(res => {
                       var url = `/ca/download/downloadFile?propertyId=${item.propertyId}`;// 文件地址
                var iframe = document.createElement('iframe')
                iframe.src = ` ${downLoadUrl + url}&token=${getToken()}`
                iframe.style.display = 'none'
                iframe.onload = function () {
                    document.body.removeAttribute(iframe)
                }
                document.body.appendChild(iframe)
          })
      })
      })
      
    } else {
      ElMessage.warning('请先选择操作数据');
    }
}
https://img-blog.csdnimg.cn/144b9e8f327a4c28888db64f5deb8e7b.png

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 前端下载文件流(可暂停、取消、查看进度)