前端下载的几种方式

对于前端的下载方式有多种,每一种都有自己不同的优略势,下面就一个一个写出对应的优缺点

a便签

a标签是最常见,也最简单的处理方式

<a href="xxx.jpg" download>点击下载</a>
优点

能解决不能直接下载浏览器可浏览的文件

缺点

必须知道下载文件地址
不能跨域下载
有兼容性问题,特别是IE
不能进行鉴权

Blod对象

blod是我第二个经常用的下载方式,将请求的二进制数据转化为blod对象,利用URL.createObjectUrl生成地址,再赋值给a标签

const xhr=new XMLHttpRequest();
xhr.open('get',xxxxx)//xxx为下载地址
xhr.responseType='blob';
xhr.send();
xhr.onreadystatechange=function(){
	if(this.readyState===4&&this.status===200){
		const url=URl.createObjectURL(xhr.response);
		const a=document.createElement('a');
		a.style.display='none';
		a.href=url;
		a.download='下载名称'
		document.body.appendChild(a);
		a.click();
		document.body.removeChild(a);
	}
}
优点

解决跨域问题
可以设置header

缺点

兼容不太友好(IE,safari)

from表单提交

from是以前经常使用的传统方式,兼容性也好

const from=document.createElemt('form');
from.action='xxx'//链接地址
from.method='get'//请求方式
from.style.display='none';
const input=document.createElement('input');
input.name='参数字段名'
input.value='参数值'
from.appendChild(input);
document.body.appendChild(from);
from.submit();//开始请求
document.body.removeChild(from);//请求完毕后清除from
优点

传统方式,兼容性好

缺点

不知道下载进度
不知道下载的什么东西

发布了6 篇原创文章 · 获赞 0 · 访问量 110

猜你喜欢

转载自blog.csdn.net/qq_40633789/article/details/104800147
今日推荐