[removed] set filename to be downloaded

后端 未结 1 1162
不思量自难忘°
不思量自难忘° 2020-12-03 23:22

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

相关标签:
1条回答
  • 2020-12-03 23:34

    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.

    0 讨论(0)
提交回复
热议问题