使用文件名保存文件Javascript [英] Save file Javascript with file name

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

问题描述

我正在使用纯Javascript编写文本编辑器。我希望这样当用户点击保存按钮时,编辑器会下载该文件。我已经部分工作了:

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:

uriContent = "data:application/octet-stream," + encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');

文件下载,但问题是该文件名为download。

The file downloads, but the problem is that the file is named 'download'.

问题:我怎样才能将文件名更改为我想要的任何内容,例如 filename.txt

Question: How could I change the name of the file to be anything I want, e.g filename.txt?

推荐答案

用锚链接替换保存按钮并设置新的动态下载属性。适用于Chrome和Firefox:

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

这是一个工作示例,名称设置为当前日期:http://jsfiddle.net/Qjvb3/

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

这里有的兼容性表格下载属性: http://caniuse.com/download

这篇关于使用文件名保存文件Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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