Using HTML5/JavaScript to generate and save a file

后端 未结 17 2044
有刺的猬
有刺的猬 2020-11-21 07:30

I\'ve been fiddling with WebGL lately, and have gotten a Collada reader working. Problem is it\'s pretty slow (Collada is a very verbose format), so I\'m going to start conv

17条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-21 07:43

    Simple solution for HTML5 ready browsers...

    function download(filename, text) {
        var pom = document.createElement('a');
        pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        pom.setAttribute('download', filename);
    
        if (document.createEvent) {
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            pom.dispatchEvent(event);
        }
        else {
            pom.click();
        }
    }
    

    Usage

    download('test.txt', 'Hello world!');
    

提交回复
热议问题