前端各种下载方法总结

前端下载的方法多种多样,面对不同的情况应有不同的解决方法,现对自己使用过的方法进行归纳总结。以下方法均需要支持跨域,除非纯前端导出

1.location.href

通过location.href直接访问后端的接口下载,后端要放开登录

2.window.open

使用_blank表示在新的页面打开,不使用则在当前页打开

window.open("http://www.baidu.com","_blank")

3.a标签

const a = document.createElement("a")
a.href = url
a.download = filename || ""
a.click()

4.通过浏览器下载文件

前端各种下载方法总结_第1张图片
上图用来表示返回值,如果后端返回的是一个二进制流,前端可以使用请求接口的方式,包括axios和fetch方法,再通过downloadFile方法下载文件,但此种方式需要支持跨域。

function directDownload(url, filename) {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = e => {
    downloadFile(xhr, filename)
  };
  xhr.send();
}
function downloadFile(res, filename) {
  const a = document.createElement('a');
  a.style.display = 'none'
  // const blob = new Blob([res.data], { type: 'mimeType' })
  const url = window.URL.createObjectURL(res.response || res.data);
  a.href = url;
  // const filename = decodeURI(res.headers['content-disposition'].split(';'))
  a.download = filename || "";
  document.body.appendChild(a)
  a.click();
  document.body.removeChild(a)
  window.URL.revokeObjectURL(url);
}

5.纯前端下载

前端导出文件

你可能感兴趣的:(javaScript,前端,javascript,html)