前端处理后端文件流并下载的几种方法

项目中经常会遇到需要导出列表内容,或者下载文件之类的需求。结合各种情况,我总结了前端最常用的三种方法来接受后端传过来的文件流并下载,针对不同的情况可以使用不同的方法
方法一
使用场景
针对后端的get请求

<a href="后端文件下载接口地址" >下载文件</a>

可以直接用标签接受后端的文件流
方法二
使用场景
针对后端的post请求 利用原生的XMLHttpRequest方法实现

function request () {
    const req = new XMLHttpRequest();
    req.open('POST', '<接口地址>', true);
    req.responseType = 'blob';
    req.setRequestHeader('Content-Type', 'application/json');
    req.onload = function() {
      const data = req.response;
      const a = document.createElement('a');
      const blob = new Blob([data]);
      const blobUrl = window.URL.createObjectURL(blob);
      download(blobUrl) ;
    };
    req.send('<请求参数:json字符串>');
  };
function download(blobUrl) {
  const a = document.createElement('a');
  a.style.display = 'none';
  a.download = '<文件名>';
  a.href = blobUrl;
  a.click();
  document.body.removeChild(a);
}
request();

方法三
使用场景
针对后端的post请求 利用原生的fetch方法实现

function request() {
  fetch('<接口地址>', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: '<请求参数:json字符串>',
  })
    .then(res => res.blob())
    .then(data => {
      let blobUrl = window.URL.createObjectURL(data);
      download(blobUrl);
    });
}
function download(blobUrl) {
  const a = document.createElement('a');
  a.style.display = 'none';
  a.download = '<文件名>';
  a.href = blobUrl;
  a.click();
  document.body.removeChild(a);
}
request();

如果后端提供的下载接口是get类型,可以直接使用方法一,简单又便捷;当然如果想使用方法二、三也是可以的,不过感觉有点舍近求远了。
如果后端提供的下载接口是post类型,就必须要用方法二或者方法三了。

猜你喜欢

转载自blog.csdn.net/weixin_42292748/article/details/85060227
今日推荐