JavaScript之PC端根据URL下载文件

判断是否是IE:
function isIE() {
  const userAgent = window.navigator.userAgent; // 取得浏览器的userAgent字符串
  const isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1; // 判断是否IE<11浏览器
  const isEdge = userAgent.indexOf('Edge') > -1 && !isIE; // 判断是否IE的Edge浏览器
  const isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1; // 判断是否IE=11浏览器
  if (isIE || isEdge || isIE11) { return true; } else { return false; }
};
下载含有url的文件:
function downloadUrlFile(url, fileName) {
    const url2 = url.replace(/\\/g, '/');
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url2, true);
    xhr.responseType = 'blob';
    // xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
    // 为了避免大文件影响用户体验,建议加loading
    // react:this.setState({downloadLoading: fileName});
    xhr.onload = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        // 获取文件blob数据并保存
        saveAs(xhr.response, fileName);
      }
      // react:this.setState({downloadLoading: ''});
    };
    xhr.send();
  }
保存到本地并自动点击:
saveAs(data, name) {
    const urlObject = window.URL || window.webkitURL || window;
    const exportBlob = new Blob([data]);
    const saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    const url = urlObject.createObjectURL(exportBlob);
    if (isIE()) {
      if (window.navigator.msSaveBlob) {
        try {
          window.navigator.msSaveBlob(data, name);
        } catch (e) {
          console.log(e);
        }
      }
    } else {
      saveLink.href = url;
      saveLink.download = name;
      saveLink.click();
      urlObject.revokeObjectURL(url);
    }
  }

最后调用:

<button onclick="downloadUrlFile(url, name)">下载</button>

 

 

posted @ 2021-08-20 17:02  阿清吖  阅读(410)  评论(0)    收藏  举报