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)

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