美文网首页
javascript实现生成并下载txt文件

javascript实现生成并下载txt文件

作者: Hi小胡 | 来源:发表于2018-02-13 17:44 被阅读1693次

方法一(支持Chrome和Firefox):

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();
    }
}

调用方式:

download("data.txt,"hello world");

方法二(支持Chrome):

function download(filename,content,contentType) {
    if (!contentType) contentType = 'application/octet-stream';
    var a = document.createElement('a');
    var blob = new Blob([content], { 'type': contentType });
    a.href = window.URL.createObjectURL(blob);
    a.download = filename;
    a.click();
}

调用方式:

download("data.txt,"hello world");

相关文章

网友评论

      本文标题:javascript实现生成并下载txt文件

      本文链接:https://www.haomeiwen.com/subject/voajtftx.html