1、实现方法
1)form表单提交
为一个下载按钮添加click事件,点击时动态生成一个表单,利用表单提交的功能来实现文件的下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
   | 
 
 
 
  function downloadFile(downloadUrl, fileName) {      const formObj = document.createElement("form")   formObj.action = downloadUrl   formObj.method = "get"   formObj.style.display = "none"      const formItem = document.createElement("input")   formItem.value = fileName    formItem.name = "fileName"       formObj.appendChild(formItem)   document.body.appendChild(formObj)   formObj.submit()    document.body.removeChild(formObj)  }
 
  | 
 
2)a标签的download
1 2 3 4 5 6
   | <a href="example.jpg" download>点击下载</a>
  <a href="example.jpg" download="test">点击下载</a> 
 
  const isSupport = 'download' in document.createElement('a');
   | 
 
3)open或location.href
1 2 3
   | window.open("downloadFile.zip")
  location.href = "downloadFile.zip"
  | 
 
4)Blob对象
调用api,将文件流转为Blob二进制对象,
思路: 发请求获取二进制数据,转化为Blob对象,利用URL.createObjectUrl生成url地址,赋值在a标签的href属性上,结合download进行下载。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
   | 
 
 
 
  downloadFile (path, name) {     const xhr = new XMLHttpRequest();     xhr.open('get', path);     xhr.responseType = 'blob';     xhr.send();     xhr.onload = function () {         if (this.status === 200 || this.status === 304) {                          if ('msSaveOrOpenBlob' in navigator) {                 navigator.msSaveOrOpenBlob(this.response, name);                 return;             }             
 
 
 
 
              
 
 
              const url = URL.createObjectURL(this.response);              const a = document.createElement('a');             a.style.display = 'none';             a.href = url;             a.download = name;             document.body.appendChild(a);             a.click();             document.body.removeChild(a);             URL.revokeObjectURL(url);         }     }; }
 
  | 
 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
   | 
  downloadFile (path, name) {     axios.get({       url: path,       method: 'get'     }).then(res => {       const blob = new Blob([res.data], { type: res.headers['content-type'] });       const url = URL.createObjectURL(blob);       const a = document.createElement('a');       a.style.display = 'none';       a.href = url;       a.download = name;       document.body.appendChild(a);       a.click();       document.body.removeChild(a);       URL.revokeObjectURL(url);     }) }
 
  | 
 
该方法不能缺少a标签的download属性的设置。
因为发请求时已设置返回数据类型为Blob类型(xhr.responseType = 'blob'),所以target.response就是一个Blob对象,打印出来会看到两个属性size和type。虽然type属性已指定了文件的类型,但是为了稳妥起见,还是在download属性值里指定后缀名,如Firefox不指定下载下来的文件就会不识别类型。
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 fortunate!