Javascript:设置要下载的文件名 [英] Javascript: set filename to be downloaded
问题描述
我正在使用插件从表格生成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 for这个特定的功能,但这个工具可以回到一个未命名的下载,如果那是可用的,因为有些东西比什么都好......
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() */
更新:添加了面向未来的IE例程
update: added future-resistant IE routine
update2:checkout GitHub上的进化版包括dataURL和Blob支持。
update2: checkout the evolved version on GitHub that includes dataURL and Blob support.
这篇关于Javascript:设置要下载的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!