Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to retain line breaks when writing text file as 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();
}

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

like image 748
Matt Avatar asked Oct 04 '13 20:10

Matt


People also ask

What is a blob JavaScript?

A Blob is an opaque reference to, or handle for, a chunk of data. The name comes from SQL databases, where it means “Binary Large Object.” In JavaScript, Blobs often represent binary data, and they can be large, but neither is required: a Blob could also represent the contents of a small text file.

Is Blob a text?

BLOB is used for storing binary data while Text is used to store large string. BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values. TEXT values are treated as nonbinary strings (character strings).


1 Answers

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

textToWrite = textToWrite.replace(/\n/g, "\r\n");
like image 124
nihlton Avatar answered Nov 03 '22 01:11

nihlton