9-5学习笔记--前端接受后端文件并下载的几种方法-转自网络

方法一get

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

直接用个标签来接受后端的文件流

方法二post
使用场景
针对后端的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();

方法二和方法三怎么取舍?
当你的项目里的接口请求全是基于XMLHttpRequest实现的,这时方法二就更加适合,只要基于你原来项目中的接口请求工具类加以扩展就行了。
当你的项目里的接口请求全是基于fetch实现的,这时方法三就更加适合,比如我现在的做的一个项目就是基于ant design pro的后台管理系统,它里面的请求类就是基于fetch的,所以我就直接用的方法三,只要在它的request.js文件中稍作修改就行。
我这里讨论的是两种原生的请求方式,如果你项目中引用了第三方请求包来发送请求,比如axios之类的,那就要另当别论了。

猜你喜欢

转载自www.cnblogs.com/sugartang/p/11470296.html
9-5