javascript 将文本文件写入为 blob 时无法保留换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19190331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:42:45  来源:igfitidea点击:

Unable to retain line breaks when writing text file as blob

javascripthtmlwebblob

提问by Matt

I have a text area that contains text that I want to output to a text file for users to download.

我有一个文本区域,其中包含要输出到文本文件供用户下载的文本。

I'm using this function to grab it when users click the save button

当用户单击保存按钮时,我正在使用此功能来抓取它

function saveTextAsFile()
{
    var textToWrite = document.getElementById("inputText").value;
    var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
    alert(textFileAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    if (window.webkitURL != null)
    {
        // Chrome allows the link to be clicked
        // without actually adding it to the DOM.
        downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
    }
    else
    {
        // Firefox requires the link to be added to the DOM
        // before it can be clicked.
        downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
        downloadLink.onclick = destroyClickedElement;
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
    }

    downloadLink.click();
}

But the line breaks aren't retained. They exist in document.getElementById("inputText").value; but not in the text file created from the blob.

但不保留换行符。它们存在于 document.getElementById("inputText").value; 但不在从 blob 创建的文本文件中。

回答by nihlton

I ran into the same problem. This seems to be working for me:

我遇到了同样的问题。这似乎对我有用:

textToWrite = textToWrite.replace(/\n/g, "\r\n");

回答by Vinu

change

改变

var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});

to

var textFileAsBlob = new Blob([textToWrite], {type:'text/plain',endings:'native'});

May not work in IE and I dont know how to fix it

可能无法在 IE 中工作,我不知道如何修复它

回答by Lambros

You should put something like that into your code.

您应该将类​​似的内容放入您的代码中。

textToWrite.replace(/\r?\n/g, '<br />');