js下载文件并监听下载进度

本文记录如何在JavaScript中实现文件下载,并监听下载进度,提高大文件下载时的用户体验。通过查阅资料,探讨了在长时下载场景下,如何展示下载状态的方法。

需求是做一个根据文件的url地址下载文件的功能,但是对于大文件来说下载周期较长,等待时间页面无反应,体验不够好,这时候就需要获取到文件的下载进度。查阅了相关资料,这里做一些记录。

/**
* 将url文件下载到本地
* @param fileUrl {String} 文件链接
* @param fileName {String} 文件名字
* @return void
*/
async function downloadFile(fileUrl,fileName) {
  let blob = await getBlob(fileUrl);
  saveFile(blob, fileName);
}
function getBlob(fileUrl) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', fileUrl, true);
    //监听进度事件
    xhr.addEventListener(
      'progress',
      function (evt) {
        if (evt.lengthComputable) {
          let percentComplete = evt.loaded / evt.total;
          // percentage是当前下载进度,可根据自己的需求自行处理
          let percentage = percentComplete * 100;
        }
      },
      false
    );
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    xhr.send();
  });
}
function saveFile(blob, fileName) {
  // ie的下载
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    // 非ie的下载
    const link = document.createElement('a');
    const body = document.querySelector('body');

    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;

    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值