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

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

问题描述

可能的重复:
使用 HTML5/Javascript 生成和保存文件

我想要一个客户端 HTML/JS 解决方案来解决这个问题 - 我有一个用户可编辑的文本区域 A、一个文本字段 B 和一个按钮 C.当用户点击 C 时,她得到一个名称等于 B 的文件下载.value 和内容等于 A.value.我查看了 this 但它没有指定如何设置文件名,我不想要像 这个.我们可以假设用户使用的是最新的 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 浏览器",这种类型的事情可以通过创建一个 带有 downloadhref 属性,然后点击它.下面的示例代码.

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');

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

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