浏览器中下载文件的场景和方案

1,141 阅读1分钟

通过a标签的download属性

<a download href="/文件名称.xls">下载文件</a>
  • 优点:使用简单、文件名称就是后台设置的名称(也可以通过download设置名称)
  • 缺点:只可以同域下载

通过设置iframe标签的src来发起资源请求

var iframe = ''
function download() {
  if (!iframe) {
    iframe = $('<iframe id="iframeDownload" style="display: none"></iframe>');
    $('body').append(iframe);
    iframe.on('load', function () {
      console.log('文件下载失败');
    });
  }
  iframe.attr('src', `文件名称.xls`);
}
</script>
  • 优点:兼容性较好、文件名称就是后台设置的名称
  • 缺点:文件生成失败了可以提示,但是拿不到后端提示信息,safari文件名称错误

ajax请求返回后通过

fetch(uri, {
      method: 'get',
      credentials: 'include'
    })
    .then(async res => {
      if (res.headers.get('content-type').startsWith('application/octet-stream')) {
        const blob = await res.blob();
        const a = document.createElement('a');
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = '文件名称';
        a.click();
        window.URL.revokeObjectURL(url);
      } else {
        const response = await res.json();
        return response
      }
    });
  • 优点:支持post请求、如果文件生成失败后端可返回json以便做后面的逻辑
  • 缺点:后端的文件名称不好获取