Javascript:设置要下载的文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16376161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript: set filename to be downloaded
提问by Noor
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
我正在使用插件从表中生成一个 csv 文件,该文件正在使用“下载”文件名下载,我该如何更改文件名,例如 dowload.csv
var csv = $("#table").table2CSV({delivery:'download'});
window.location.href = 'data:text/csv;charset=UTF-8,'+ encodeURIComponent(csv);
回答by dandavis
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...
在撰写本文时,您需要 chrome、firefox 或 IE10 才能获得该特定功能,但如果仅此而已,此工具会退回到未命名的下载,因为有总比没有好...
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
更新:添加了面向未来的 IE 例程
update2: checkout the evolved version on GitHubthat includes dataURL and Blob support.