当前位置:主页 > 网页前端 > JavaScript代码 >

JavaScript 用fetch 实现异步下载文件功能

时间:2020-12-02 11:58:36 | 栏目:JavaScript代码 | 点击:

废话不多说了,直接给大家贴代码了,具体代码如下所示:

<!DOCTYPE html> 
<html> 
<head> 
  <meta charset="utf-8"> 
  <title>sample</title> 
</head> 
<body> 
  <button id='btn'>下载</button> 
  <span id='status'></span> 
</body> 
<script> 
  var url = "http://localhost/sample/upload.php"; 
  document.getElementById('btn').onclick = function() { 
    document.getElementById('status').innerHTML = '下载中'; 
    fetch(url).then(res => res.blob().then(blob => { 
      var a = document.createElement('a'); 
      var url = window.URL.createObjectURL(blob); 
      var filename = res.headers.get('Content-Disposition'); 
      a.href = url; 
      a.download = filename; 
      a.click(); 
      window.URL.revokeObjectURL(url); 
      document.getElementById('status').innerHTML = '下载完成'; 
    })); 
  }; 
</script> 
</html> 

总结

您可能感兴趣的文章:

相关文章