如何生成多行下载文件 Javascript

How To Generate Multiline Download File Javascript

我正在为数据包创建一个 Minecraft .mcfunction 文件,用户可以根据输入的 .mcfunction 功能信息生成该文件。我已经完成了其他所有事情,但似乎无法制作可下载的文件。我做了一些研究,发现下面显示了这段代码,问题是文件一直在一行上打印所有内容,而且我不确定如何将它从 .txt 更改为 .mcfunction

<script text="text/javascript">

function Download(name, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', name);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

</script>

有谁知道如何让这个显示为多行文本,而不是打印在一行上?我知道我输入的字符串变量是正确的,因为我可以看到它在按 f12 时发送到控制台后的样子。它在控制台上准确地显示为多行,但在我下载文件时不会显示为多行。关于如何解决这个问题有什么想法吗?

编辑: 我还看到了一些关于添加这行代码的内容,但不确定我应该把它放在哪里,或者如何在此函数中使用它。

downloadURI("data:text/html," + parsed.join("\r\n"), "name.txt");

编辑: 刚刚发现在 notepad++ 中打开文件显示正确._.

您需要将 \n 替换为 \r\n,以便它们在 Windows 记事本中显示。至于更改文件名,请尝试 name = name.substr(0, name.lastIndexOf(".")) + ".mcfunction";

已解决:

<script text="text/javascript">


function ninjaShopDownload(name, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain+ parsed.join("\r\n");charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', name+".mcfunction");

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

</script>

我会保留它以防其他人需要它。