例如我服务器根目录为/var/www/,如何点击按钮触发一个事件去下载该目录的test.txt文件,用js实现,各位有经验的前辈有比较好的方法吗?
最好是有比较详细的代码,谢谢啦!
之前我在网上找了一个资料,但是用IE浏览器发现是直接打开文件,而不是下载。
window.downloadFile = function (sUrl) {
alert("sUrl = "+sUrl);
//iOS devices do not support downloading. We have to inform user about this.
if (/(iP)/g.test(navigator.userAgent)) {
alert('设备不支持文件下载!');
return false;
}
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
alert("Creating new link node.");
var link = document.createElement('a');
link.href = sUrl;
alert("link.download = "+link.download);
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);
alert(fileName);
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;
}