js下载文件

Posted 张书达

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js下载文件相关的知识,希望对你有一定的参考价值。

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 = document.createElement(‘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 (document.createEvent) {
var e = document.createEvent(‘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 = navigator.userAgent.toLowerCase().indexOf(‘chrome‘) > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf(‘safari‘) > -1;

以上是关于js下载文件的主要内容,如果未能解决你的问题,请参考以下文章

FileSaver.js 文件下载

Node.js之文件下载

使用js或者C#怎么实现下载弹出页面中的下载框的方式下载文件?

JS生成下载文件

Socket.io.js文件下载

js多文件下载和多文件分文件夹打包下载并重命名