16

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

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

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

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

4

3 回答 3

37

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

textToWrite = textToWrite.replace(/\n/g, "\r\n");
于 2014-04-23T19:35:38.553 回答
3

改变

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

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

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

于 2018-09-11T14:44:22.297 回答
-5

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

textToWrite.replace(/\r?\n/g, '<br />');
于 2013-10-06T15:13:38.287 回答