简体   繁体   中英

How To Generate Multiline Download File Javascript

I'm creating a Minecraft .mcfunction file for a datapack that the user can generate based on inputed info of what the .mcfunction does. I have everything else done, but can't seem to make a downloadable file. I did some research and found this code shown below, problem is the file keeps printing everything on one line, also I'm not sure how to change it from .txt to .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>

Does anyone know how to make this show as multi-line text, and not print on one line? I know the string variable I'm inputting is correct because I can see what it looks like after getting sent to console when pressing f12. it shows on multiple lines on console accurately, but won't show up as multiple lines when I download the file. any ideas on how to fix this?

Edit: I also saw something about adding this line of code, but not sure where I'm supposed to put it, or how to use it in this function.

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

Edit: just found out opening the file in notepad++ displays correctly ._.

You need to replace your \\n s with \\r\\n s for them to display as you wish in Windows Notepad. As for changing the filename, try name = name.substr(0, name.lastIndexOf(".")) + ".mcfunction";

Solved:

<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>

I will leave this up in-case anyone else needs it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM