Calthabis
Calthabis

Reputation: 81

Download file/url using Javascript

I am trying to automatically download a file using javascript by creating a link and the clicking it. That works but using the download attribute, to specify the name the file will have, does not work.

Im using the code below

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();

Is there a way to make this work?

Upvotes: 2

Views: 16280

Answers (1)

Jingsong Zhao
Jingsong Zhao

Reputation: 41

Here is my code using XMLHttpRequest ,tested in IE10+ , firefox ,and 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);
}

Upvotes: 4

Related Questions