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

链接是服务器地址可能会跨域
方法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",
  })

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值