前端文件下载方式

目前a标签下载文件已经成为主流,并且用户体验较好,因此本人没有对其他下载方式深入研究过。

1.同源url

同源且下载地址就是一个文件时,直接设置a标签的href属性为下载地址,并且为a标签添加download属性即可。如果非同源url,那么这种方式会直接将文件在新的页面打开,而非下载。

2.非同源url

这里介绍三种发送请求的方式和一种不发送请求的方式。以下4种方式都不会打开文件而是直接下载,由于是发送网络请求,因此需要在服务端解决跨域问题才能使用这种方式。以下请求都以axios为例:

2.1利用Blob对象(推荐)

//url是下载地址,fileName是下载时的文件名
function downloadFileBlob(url,fileName){
  axios.get(url, {responseType: 'blob'}).then(res=>{
    console.log(res);
    let url=URL.createObjectURL(res.data);
    console.log(url);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    //download属性可以设置下载到本地时的文件名称,经测试并不需要加文件后缀
    a.setAttribute('download', fileName);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    //释放内存
    URL.revokeObjectURL(url);
  })
}

打印结果:


QQ截图20230525163134.png

2.2利用base64

适用于很小的文件

//url是下载地址,fileName是下载时的文件名
function downloadFile(url,fileName){
  axios.get(url, {responseType: 'blob'}).then(res=>{
    console.log(res);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = URL.createObjectURL(res.data);
    //download属性可以设置下载到本地时的文件名称,经测试并不需要加文件后缀
    a.setAttribute('download', fileName);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  })
}

打印结果:


QQ截图20230525162951.png

2.3利用arraybuffer(不推荐)

其实也是转为base64,只是更麻烦一些,需要根据响应头的content-type属性手动拼接base64字符串。而且btoa也是一个过时的api,因此不推荐使用

function downloadArraybuffer(url,fileName){
  axios.get(url, {responseType: 'arraybuffer'}).then(res=>{
    console.log(res);
    let href='data:'+res.headers['content-type']+';base64,'+window.btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
    console.log(href);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = href;
    a.setAttribute('download', fileName);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  })
}

打印结果:


QQ截图20230525164749.png

2.4特殊情况,返回的数据type为application/octet-stream

QQ截图20230525181259.png

这种情况下,直接使用a标签并在url后拼接'?response-content-type=application/octet-stream'字符串就能实现下载。文件名无法修改,content-disposition字段中下发的filename就是文件名。使用2.123的三种方式下载的文件没有后缀。

function downloadFile(url,fileName){
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url+'?response-content-type=application/octet-stream';
  a.download='';
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}
以上就是我对前端文件下载的总结,可能理解不是很深刻,如有错误欢迎指正

参考文献:
https://blog.csdn.net/love_aya/article/details/115211470
https://blog.csdn.net/weixin_46801282/article/details/123386264

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容