JavaScript实现文件批量下载(适用IE、Chrome、Edge等浏览器)

//判断浏览器类型
function isIE()
{ 
if(!!window.ActiveXObject || "ActiveXObject" in window) 
	return true; 
else 
	return false; 
}


//IE浏览器保存文本框内容
function IEDownloadFile(url) {
	var fileName = url.substring(url.lastIndexOf("/")+1);
	var type = "text/plain; charset=UTF-8";
	var blob = typeof File === 'function'
		? new File([url], fileName, { type: type })
		: new Blob([url], { type: type });
	if (typeof window.navigator.msSaveBlob !== 'undefined') {
		// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
		window.navigator.msSaveBlob(blob, fileName);
	} else {
		var URL = window.URL || window.webkitURL;
		var downloadUrl = URL.createObjectURL(blob);

		if (fileName) {
			// use HTML5 a[download] attribute to specify filename
			var a = document.createElement("a");
			// safari doesn't support this yet
			if (typeof a.download === 'undefined') {
				window.location = downloadUrl;
			} else {
				a.href = downloadUrl;
				a.download = fileName;
				document.body.appendChild(a);
				a.click();
			}
		} else {
			window.location = downloadUrl;
		}
	}
}

//chrome等下载文件方法
function downloadFile(url){
	//alert(url);
	const iframe = document.createElement("iframe");
	iframe.style.display = "none";  // 防止影响页面
	iframe.style.height = 0;  //防止影响页面
	iframe.src = url; 
	document.body.appendChild(iframe);  // 这一行必须,iframe挂在到dom树上才会发请求
	setTimeout(function(){
	iframe.remove();
	}, 5 * 60 * 1000);
}
//调用下载
if(isIE){
	IEDownloadFile(files[i]);
}else{
	downloadFile(files[i]);
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值