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

  <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([res], { 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('请先选择操作数据');
    }
}

在这里插入图片描述

要在前端下载文件并获取下载进度,可以使用 XMLHttpRequest 对象来实现。以下是一个简单的示例代码: ```javascript function downloadFile(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.onload = function() { if (xhr.status === 200) { resolve(xhr.response); } else { reject(new Error('File download failed')); } }; xhr.onprogress = function(event) { if (event.lengthComputable) { const progress = Math.round((event.loaded / event.total) * 100); console.log(`Download progress: ${progress}%`); } }; xhr.onerror = function() { reject(new Error('File download failed')); }; xhr.send(); }); } // 示例用法 const fileUrl = 'https://example.com/file.pdf'; downloadFile(fileUrl) .then(blob => { // 下载完成后的处理 const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'file.pdf'; a.click(); }) .catch(error => { console.error(error); }); ``` 上述代码通过 XMLHttpRequest 发起了一个 GET 请求来下载文件,设置了 `responseType` 为 `blob`,这样可以获取到文件的二进制数据。通过监听 `onprogress` 事件,可以获取到下载进度的信息。在下载完成后,将下载文件转换为 Blob 对象,并创建一个隐藏的 `<a>` 元素来实现文件下载。 注意:由于涉及到跨域请求,请确保服务器端已经设置了正确的 CORS 头部,允许前端访问下载文件的资源。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值