JavaScript 下载文件

ajax 下载文件

let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.xxx.com/bbb.zip', true);
// 这部至关重要,命令xhr返回给你的时blob(二进制大对象)类型的数据
xhr.responseType = 'blob';
xhr.send()
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
        const aTag = document.createElement('a')
        aTag.href = URL.createObjectURL(this.response)
        aTag.download = 'aaa.zip'
        aTag.click()
  }
}

使用<a>标签点击下载

<a href="../../static/xxx.xlsx" download="xxx.xlsx">下载</a>

直接点击可以下载,需要注意的是download属性,当不加download属性时,如果文件格式为txt、pdf、jpg等浏览器支持直接打开的文件格式,那么不会下载,而是浏览器直接打开;添加download属性之后,就会下载,并且下载文件默认命名为你download属性的值。

使用window.open()

window.open("../../static/xxx.xlsx");// 下载本地文件
window.open("https://mp.csdn.net/postedit/static/xxx.xlsx");// 下载网络文件

 注:中文名未测试

fetch 下载文件

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <button onclick="download()">下载</button>
  <script>
    function downloadMp3(filePath) {
      fetch(filePath).then(res => res.blob()).then(blob => {
        const a = document.createElement('a');
        document.body.appendChild(a)
        a.style.display = 'none'
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = 'xxxx.mp3';
        a.click();
        document.body.removeChild(a)
        window.URL.revokeObjectURL(url);
      });
    }
    function download() {
      this.downloadMp3('http://m10.music.com/708b9cbb995e5dfb5b27295c1.m4a');
    }
  </script>
</body>
</html>

Blob下载文件

<a id="h">点此进行下载</a>
<!-- js部分 -->
<script>
  var blob = new Blob(["Hello World"]);
  var url = window.URL.createObjectURL(blob);
  var a = document.getElementById("h");
  a.download = "helloworld.txt";
  a.href = url;
</script>

 

我们可以通过window.URL.createObjectURL,接收一个Blob(File)对象,将其转化为Blob URL,然后赋给 a.download属性,然后在页面上点击这个链接就可以实现下载了。

备注:download属性不兼容IE, 对IE可通过window.navigator.msSaveBlob方法或其他进行优化(IE10/11)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章