Save content of textarea as plain txt with .csv ex

2019-02-20 00:28发布

问题:

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:

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>