Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: set filename to be downloaded

Tags:

javascript

csv

I'm using a plugin to generate a csv file from a table, the file is being downloaded with a "download" filename, how can I change the filename e.g. as dowload.csv

var csv = $("#table").table2CSV({delivery:'download'});
window.location.href = 'data:text/csv;charset=UTF-8,'+ encodeURIComponent(csv);
like image 609
Noor Avatar asked May 04 '13 15:05

Noor


1 Answers

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 = "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 = "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.

like image 194
dandavis Avatar answered Sep 25 '22 02:09

dandavis