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

时间:2013-10-04 20:36:23

标签: javascript html web blob

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

当用户点击保存按钮

时,我正在使用此功能抓取它
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创建的文本文件中。

3 个答案:

答案 0 :(得分:30)

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

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

答案 1 :(得分:0)

更改

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

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

可能无法在IE中工作,我也不知道如何解决

答案 2 :(得分:-5)

你应该把这样的东西放到你的代码中。

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