如何保存文件从textarea在Javascript中的名称? [英] How to save file from textarea in Javascript with a name?

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

问题描述


可能重复:

使用HTML5 / Javascript生成和保存文件

我想要一个客户端HTML / JS解决方案来解决这个问题 - 我有一个用户可编辑的文本区域A,一个文本框B和一个按钮C.当用户点击C时,她得到一个文件下载名称等于B.value,内容等于A.value。我查看了这个,但是它没有指定如何设置文件名,而且我不想要像这个。我们可以假设用户是最新的Chrome浏览器(这对我的团队来说是一个小工具)

I want a client side HTML/JS solution to solve this problem - I have a user-edittable textarea A, a textfield B and a button C. When user clicks on C, she gets a file download with name equal to B.value and contents equal to A.value. I looked at this but it does not specify how to set the filename and I don't want a Flash solution like this. We can assume users are on latest Chrome browser (it's a little tool for my team)

推荐答案

因为我们可以假设用户是在最新的Chrome浏览器上,这种类型的事情可以通过创建一个< a> 与属性下载 href ,然后点击它。
下面的示例代码

Because "we can assume users are on latest Chrome browser", this type of thing can be done by creating an <a> with attributes download and href, and then clicking on it. Example code below.

var Download = {
    click : function(node) {
        var ev = document.createEvent("MouseEvents");
        ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        return node.dispatchEvent(ev);
    },
    encode : function(data) {
            return 'data:application/octet-stream;base64,' + btoa( data );
    },
    link : function(data, name){
        var a = document.createElement('a');
        a.download = name || self.location.pathname.slice(self.location.pathname.lastIndexOf('/')+1);
        a.href = data || self.location.href;
        return a;
    }
};
Download.save = function(data, name){
    this.click(
        this.link(
            this.encode( data ),
            name
        )
    );
};

Download.save('hello world', 'my_file.txt');

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

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