Save content of textarea as plain txt with .csv ex

2019-02-20 00:47发布

Is there a way to save content as a txt file with a csv file extension using HTML5 ?
It shouldn't be a real csv.

Something like {type:'text/csv'}; wont work where {type:'text/plain'}; does.

1条回答
闹够了就滚
2楼-- · 2019-02-20 01:16

The a tag's new download property can work to your advantage here. More information.

Proof of concept:

<!doctype html>
<html>
    <head>
        <script type="text/javascript">
            function save() {
                var a = document.createElement('a');
                with (a) {
                    href='data:text/csv;base64,' + btoa(document.getElementById('csv').value);
                    download='csvfile.csv';
                }
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
            }
        </script>
    </head>
    <body>
        <textarea id="csv"></textarea><button onclick="save()">Save</button>
    </body>
</html>
查看更多
登录 后发表回答