将文本文件写为blob时无法保留换行符 [英] Unable to retain line breaks when writing text file as blob

查看:896
本文介绍了将文本文件写为blob时无法保留换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

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

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

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

这篇关于将文本文件写为blob时无法保留换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆