使用 javascript API -- fetch 實現文件下載功能


下載原理

下載原理很簡單,就是模擬 a 標簽的點擊下載,我們都知道 ajax 不支持下載文件功能,是因為 ajax 只能用來傳輸字符型數據,所以在過去無法使用 ajax 來下載文件。
xhr2 可以把 response 保存為 blob,下載結束后,為這個 blob 創建一個 URL,跳轉到這個URL,或使用 anchor element with download property ,瀏覽器會彈出保存框。如果文件很大的話,還需要用到 filesystem API,因為 blob 是存在內存中的。(來自知乎:魯小夫

簡單的實現方式

<!DOCTYPE html> 
<html> 
<head> 
  <meta charset="utf-8"> 
  <title>sample</title> 
</head> 
<body> 
  <button id='download'>下載</button> 
  <span id='status'></span> 
</body> 
<script> 
  var url = "http:// your files link"; 
  document.querySelector('#download').onclick = function() { 
    document.querySelector('#status').innerHTML = '文件下載中...'; 
    fetch(url).then(res => res.blob().then(blob => { 
      var a = document.createElement('a'); 
      var url = window.URL.createObjectURL(blob);   // 獲取 blob 本地文件連接 (blob 為純二進制對象,不能夠直接保存到磁盤上)
      var filename = res.headers.get('Content-Disposition'); 
      a.href = url; 
      a.download = filename; 
      a.click(); 
      window.URL.revokeObjectURL(url); 
      document.querySelector('#status').innerHTML = '下載完成'; 
    })); 
  }; 
</script> 
</html>

關於 window.URL.createObjectURL(blob)window.URL.revokeObjectURL(objectURL)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM