Javascript在下载中设置文件 [英] Javascript set file in download

查看:135
本文介绍了Javascript在下载中设置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用插件从表中生成一个csv文件,该文件正在下载一个下载文件名,如何更改文件名。 as dowload.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);


推荐答案

我写了一个工具,到本地机器的下载文件夹,如果这可能在客户端的机器上。

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.

在本文写作,您需要chrome,firefox或IE10但这个工具落回到一个未命名的下载,如果这是所有的可用,因为某事比没有更好...

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

供您使用:

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

和魔术代码:

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() */

update2:checkout GitHub上的演进版本包含dataURL和Blob支持。

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

这篇关于Javascript在下载中设置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆