JavaScript文件:(五)文件下载

2022-07-26  本文已影响0人  fanren

一、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接口下载

上一篇下一篇

猜你喜欢

热点阅读