美文网首页
react 之简单文件下载

react 之简单文件下载

作者: wilsonLwx | 来源:发表于2022-01-06 19:22 被阅读0次

无需赘言,直接看代码示例:

const downloadFile = () => {
  const file_path = 'your file name'
  const URL = 'download url'
  // 创建a标签
  let a= document.createElement("a");
  // 设置下载文件的文件名
  a.download = file_path;
  // 设置下载文件url
  a.href = URL;
  // 设置点击事件
  a.click();
}

以上的代码会遇到a标签download属性不生效的情况,这是由于跨域造成的,为了解决跨域问题,还有另外的一个方法,就是请求接口,代码如下:

const downloadFile = () => {
  const url = 'your url/?file_path='your file path'
  fetch(url, {
    method: 'get',
    responseType: 'blob'
  }).then(res => {
    // 获取blob文件流
    return res.blob();
  }).then(blob => {
    let a = document.createElement('a');
    // 通过 blob 对象获取对应的 url
    let url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = 'file_name.gds';
    a.click();
    a.remove();
  })
}

这样你的请求通过setupProxy.js就可以解决跨域问题了。

相关文章

网友评论

      本文标题:react 之简单文件下载

      本文链接:https://www.haomeiwen.com/subject/zvorcrtx.html