美文网首页
JavaScript文件:(五)文件下载

JavaScript文件:(五)文件下载

作者: fanren | 来源:发表于2022-07-26 09:43 被阅读0次

    一、a标签

    const el = document.createElement('a');
    el.style.display = 'none';
    el.setAttribute('target', '_blank');
    el.href = url;
    document.body.appendChild(el)
    el.click();
    document.body.removeChild(el);
    

    二、window.open

    let url = '下载地址'
    window.open(url, '_blank')
    

    三、location.href

    let url = '下载地址'
    window.location.href = url;
    

    四、fetch接口

    let url = '文件下载地址';
    let options = {
      method: "GET",
    }
    fetch(new Request(url, options))
      .then((response) => {
        return response.blob();
      })
      .then((blob) => {
        let fileName = 'text.pdf';
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          // IE浏览器
          window.navigator.msSaveOrOpenBlob(blob, fileName);
        } else {
          // Non-IE (chrome, firefox etc.)
          let url = window.URL.createObjectURL(blob);
    
          var link = document.createElement("a");
          link.href = url;
          link.download = decodeURI(fileName);
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
      });
    

    五、ajax接口下载

    相关文章

      网友评论

          本文标题:JavaScript文件:(五)文件下载

          本文链接:https://www.haomeiwen.com/subject/eangirtx.html