Js下载⽂件到本地(兼容多浏览器)
在客户端通过js下载⽂件,试过⼏种下载⽅式,iframe⽅式仅限于IE浏览器,window.open(url),location.href=url 这两种⽅式在chrome浏览器还会是直接打开⽂件⽽不是下载,百度N久没有结果,在⾕歌还是到答案了,在此。
window.downloadFile = function (sUrl) {
//iOS devices do not support downloading. We have to inform user about this.
if (/(iP)/g.test(navigator.userAgent)) {
alert('Your device does not support files downloading. Please try again in desktop browser.');
return false;
}
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = ateElement('a');
link.href = sUrl;
if (link.download !== undefined) {
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (ateEvent) {
var e = ateEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
if (sUrl.indexOf('?') === -1) {
sUrl += '?download';
}
window.open(sUrl, '_self');
return true;
}
window.downloadFile.isChrome = LowerCase().indexOf('chrome') > -1;
chrome直接下载window.downloadFile.isSafari = LowerCase().indexOf('safari') > -1;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。