使用Javascript下载文件/url

Download file/url using Javascript

本文关键字:url 文件 下载 Javascript 使用      更新时间:2023-09-26

我正试图通过创建一个链接并单击它来使用javascript自动下载一个文件。这是有效的,但使用下载属性来指定文件的名称是无效的。

我使用下面的代码

var a = document.createElement("a")
a.download = "hellooo.png"
a.href = "http://icons.iconarchive.com/icons/yellowicon/game-stars/256/Mario-icon.png";
a.click();

有没有办法做到这一点?

这是我使用XMLHttpRequest的代码,在IE10+、firefox和Chrome 中进行了测试

function download(url, fileName) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onprogress = function(event) {
        if (event.lengthComputable) {
            var percentComplete = (event.loaded / event.total)*100;
            //yourShowProgressFunction(percentComplete);
        } 
    };
    xhr.onload = function(event) {
        if (this.status == 200) {
            _saveBlob(this.response, fileName);
        }
        else {
            //yourErrorFunction()
        }
    };
    xhr.onerror = function(event){
        //yourErrorFunction()
    };
    xhr.send();
}

function _saveBlob(response, fileName) {
    if(navigator.msSaveBlob){
        //OK for IE10+
        navigator.msSaveBlob(response, fileName);
    }
    else{
        _html5Saver(response, fileName);
    }
}
function _html5Saver(blob , fileName) {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    var url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    document.body.removeChild(a);
}