web小白请教,如何利用js url 下载服务器端文件?

例如我服务器根目录为/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;
}

可以设置强制下载而不打开

浏览器打开一般有两种状态,一个是预览,一个是下载,应该是这个问题,还没用过js做下载,都是在服务器端进行控制的

1.通过window.open

window.open('https://1.1.1.1/test.txt')
2.通过get表单请求

var $form = $('<form method="GET"></form>')
$form.attr('action', 'http://1.1.1.1/test.txt')
 $form.appendTo($('body'))
 $form.submit()