22

Could someone help me save the contents of a HTML5 textArea to file, preferably using JavaScript?

<textarea id="textArea">
   Notes here...
</textarea>
<button type="button" value="save"> Save</button>
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
FootsieNG
  • 809
  • 3
  • 12
  • 27
  • To a local file? (http://www.html5rocks.com/en/tutorials/file/filesystem/) or on a remote server? – Alex K. Jan 31 '14 at 11:37

4 Answers4

29

That should do it.

function saveTextAsFile() {
  var textToWrite = document.getElementById('textArea').innerHTML;
  var textFileAsBlob = new Blob([ textToWrite ], { type: 'text/plain' });
  var fileNameToSaveAs = "file.txt"; //filename.extension

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

var button = document.getElementById('save');
button.addEventListener('click', saveTextAsFile);

function destroyClickedElement(event) {
  // remove the link from the DOM
  document.body.removeChild(event.target);
}
#textArea {
  display: block;
  width: 100%;
}
<textarea id="textArea" rows="3">
   Notes here...
</textarea>
<button type="button" value="save" id="save">Save</button>

JSFiddle

engincancan
  • 2,442
  • 2
  • 28
  • 43
  • This didn't work for me, the solution was to call the function with `button onclick` cf http://stackoverflow.com/a/41965468/3154274 – MagTun Jan 31 '17 at 19:06
  • textToWrite is a textarea's innerHTML, not the textarea itself. I will add an edit. Thanks for the solution though. – Maciej Krawczyk Mar 09 '18 at 13:45
  • 1
    Thanks a lot for the solution! It helped me a lot. Just one point about the content saved in the file: I think it's wrong because we shouldn't read the `innerHTML` property of the textarea but the `value` property instead. – Patrick Janser Sep 23 '20 at 22:10
13

A simplified version of the code in the answers:

function download(){
    var text = document.getElementById("my-textarea").value;
    text = text.replace(/\n/g, "\r\n"); // To retain the Line breaks.
    var blob = new Blob([text], { type: "text/plain"});
    var anchor = document.createElement("a");
    anchor.download = "my-filename.txt";
    anchor.href = window.URL.createObjectURL(blob);
    anchor.target ="_blank";
    anchor.style.display = "none"; // just to be safe!
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
 }

and the html:

<textarea id="my-textarea">
   Notes here...
</textarea>
<button type="button" onclick="download()">Save</button>
A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
  • I like the simplicity. However newline characters do not appear in the downloaded file - all text is run together on one line. – youcantryreachingme Feb 25 '18 at 02:37
  • 1
    I found a fix for your code at this question: https://stackoverflow.com/questions/19190331/unable-to-retain-line-breaks-when-writing-text-file-as-blob – youcantryreachingme Feb 25 '18 at 02:46
  • 3
    The fix would be to add this line before your blob declaration: text = text.replace(/\n/g, "\r\n"); – youcantryreachingme Feb 25 '18 at 02:46
  • Thanks for summarising. This works nicely but doesn't work on iOS which just displays the blob in a new browser window. Any suggestions on how to get it to work properly and take the suggested filename? – Dean Jenkins Aug 20 '21 at 16:03
2

I tested engincancan's answer, and it was almost there, but not quite. First of all, the file format for "ecc.plist" was not recognizable anywhere. Second of all, in order for the code to work on the desktop in Safari, Chrome, and Firefox, you have to use an existing anchor tag and not create one (document.createElement('a')). The destroyClickedElement approach only works in Chrome, because it is so forgiving and lenient. And, in order for the download to work in Firefox, you have to have document.body.appendChild(downloadLink.download);

I also had wanted to save my local storage text to a file for download and the code works on desktop for Safari, Chrome and Firefox on Mac. However, I think it is impossible in iOS to save the Blob() anywhere with Chrome or Firefox. It does work, interestingly enough in Safari. For example, I can save the text file to my Wunderlist app. Here is the link my repo on Github: The Cat Whisperer on Github gh-pages

Here is the JavaScript code:

const fileDownloadButton = document.getElementById('save');
function localStorageToFile() {
    const csv = JSON.stringify(localStorage['autosave']);
    const csvAsBlob = new Blob([csv], {type: 'text/plain'});
    const fileNameToSaveAs = 'local-storage.txt';
    const downloadLink = document.getElementById('save');
    downloadLink.download = fileNameToSaveAs;
    if (window.URL !== null) {
        // Chrome allows the link to be clicked without actually adding it to the DOM
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
    } else {
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
        downloadLink.style.display = 'none';
        // add .download so works in Firefox desktop.
        document.body.appendChild(downloadLink.download);
    }
    downloadLink.click();
}
// file download button event listener
fileDownloadButton.addEventListener('click', localStorageToFile);      
Community
  • 1
  • 1
Maria Campbell
  • 418
  • 5
  • 9
-1
<textarea id = "textArea">
    Notes here...
</textarea>

<button onclick="savetextarea()" type="button">Save</button>

<script>
    function savetextarea(){
        var txt = document.getElementById("textArea").value;
        document.getElementById("saveinput").value = txt;
        document.forms["aForm"].submit();
    }
</script>

<form action="savecontent" name="aForm">
    <input id="saveinput" type="hidden" name="filecontent" value="">
</form>
  • 3
    This will only work if there's something on server side handling the actual saving of the file... so it does not answer the question – MrAn3 Oct 09 '16 at 22:06