使用文件名保存文件 Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7717851/
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
Save file Javascript with file name
提问by skimberk1
I'm working on a text editor in pure Javascript. I'd like it so that when the user clicks the 'Save' button, the editor downloads the file. I've already got this partly working:
我正在使用纯 Javascript 编写文本编辑器。我希望这样当用户单击“保存”按钮时,编辑器会下载文件。我已经部分工作了:
uriContent = "data:application/octet-stream," + encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');
The file downloads, but the problem is that the file is named 'download'.
文件下载,但问题是文件名为“下载”。
Question: How could I change the name of the file to be anything I want, e.g filename.txt
?
问题:如何将文件名更改为我想要的任何名称,例如filename.txt
?
采纳答案by Arthur Clemens
Replace your "Save" button with an anchor link and set the new download
attribute dynamically. Works in Chrome and Firefox:
用锚链接替换“保存”按钮并download
动态设置新属性。适用于 Chrome 和 Firefox:
var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");
Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/
这是一个名称设置为当前日期的工作示例:http: //jsfiddle.net/Qjvb3/
Here a compatibility table for download
attribute: http://caniuse.com/download
这是download
属性的兼容性表:http: //caniuse.com/download
回答by Reddy
function saveAs(uri, filename) {
var link = document.createElement('a');
if (typeof link.download === 'string') {
document.body.appendChild(link); // Firefox requires the link to be in the body
link.download = filename;
link.href = uri;
link.click();
document.body.removeChild(link); // remove the link when done
} else {
location.replace(uri);
}
}
回答by James Hill
Use the filename
property like this:
filename
像这样使用属性:
uriContent = "data:application/octet-stream;filename=filename.txt," +
encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');
EDIT:
编辑:
Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?
显然,没有可靠的方法可以做到这一点。请参阅:在使用 data: URI 时,是否有任何方法可以指定建议的文件名?