Javascript: set filename to be downloaded

i wrote a tool you can use to save a file to the downloads folder of the local machine with a custom filename, if that’s possible on the client’s machine.

as of this writing, you need chrome, firefox, or IE10 for that specific capability, but this tool falls-back to an un-named download if that’s all that’s available, since something is better than nothing…

for your use:

download(csv, "dowload.csv", "text/csv");

and the magic code:

function download(strData, strFileName, strMimeType) {
    var D = document,
        a = D.createElement("a");
        strMimeType= strMimeType || "application/octet-stream";


    if (navigator.msSaveBlob) { // IE10
        return navigator.msSaveBlob(new Blob([strData], {type: strMimeType}), strFileName);
    } /* end if(navigator.msSaveBlob) */


    if ('download' in a) { //html5 A[download]
        a.href = "https://stackoverflow.com/questions/16376161/data:" + strMimeType + "," + encodeURIComponent(strData);
        a.setAttribute("download", strFileName);
        a.innerHTML = "downloading...";
        D.body.appendChild(a);
        setTimeout(function() {
            a.click();
            D.body.removeChild(a);
        }, 66);
        return true;
    } /* end if('download' in a) */


    //do iframe dataURL download (old ch+FF):
    var f = D.createElement("iframe");
    D.body.appendChild(f);
    f.src = "https://stackoverflow.com/questions/16376161/data:" +  strMimeType   + "," + encodeURIComponent(strData);

    setTimeout(function() {
        D.body.removeChild(f);
    }, 333);
    return true;
} /* end download() */

update: added future-resistant IE routine

update2: checkout the evolved version on GitHub that includes dataURL and Blob support.

Leave a Comment