0
点赞
收藏
分享

微信扫一扫

【2022-2-12】前端下载文件的几种方式

程序员伟杰 2022-02-12 阅读 56

链接是服务器地址可能会跨域
方法1:不会涉及跨域

const link = document.createElement('a');
          console.log(location.origin+src)
          link.href = "http://www.xxx.com:8000/frame/download.do?id=38e07c7b-5743-4d1e-a5af-f486a7df401e";
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();

方法2:会跨域【未亲测成功】,jquery的ajax,需要依赖jquery

$.ajax({
  method: "get",
   url:src,
   responseType: "blob",
   success:(response)=>{
     console.log(response.data)
     const url = window.URL.createObjectURL(new Blob([response.data]));
     console.log(url);
     const link = document.createElement('a');
     link.href = url;
     link.setAttribute('download', fileName);
     document.body.appendChild(link);
     link.click();
     window.URL.revokeObjectURL(url);
   }
 })

方法3:会跨域【未亲测成功】原生请求方式

var xhr = new XMLHttpRequest();
xhr.open('GET', src, true);    // 也可以使用POST方式,根据接口
xhr.responseType = "blob";  // 设置返回类型blob
// 定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function () {     // 请求完成
  if (this.status === 200) {       // 返回200
    var blob = this.response;
    console.log(blob)
    var reader = new FileReader();
    reader.readAsDataURL(blob);  // 转换为base64,可以直接放入a标签的href
    reader.onload = function (e) {         // 转换完成,创建一个a标签用于下载
      var a = document.createElement('a');
      a.download = fileName;
      a.href = e.target.result;
      document.body.append(a);  // 修复firefox中无法触发click
      a.click();
      a.remove &&  a.remove();
    }
  }
};   // 发送ajax请求
xhr.send()

方法4:
直接在a标签上写href的值,并且设置download

<a href="url" download>{{item.value}}</a>

方法5:

window.open(url)

方法6:

window.location = url

方法7
axios,一般会在vuecli的时候使用,当然fetch等等请求方式也可以哦。

axios({
    method: "get",
    url,
    params,
    responseType: "blob",
  })

欢迎大家分享更多的下载方式

举报

相关推荐

0 条评论