Reading and Creating Text Files Using the HTML5 File API

by Hendy T

HTML

<button type="button" id="btn-open" class="btn-copy">Open...</button>
<button type="button" id="btn-save" class="btn-copy">Save</button>
<textarea id="textarea1" rows="10"></textarea>
<input accept=".txt,.csv,.xml" id="file-browser" type="file" />

CSS

#textarea1 {
    display: block;
    width: 100%;
}
#file-browser {
    display: none;
}

JavaScript

document.getElementById('btn-open').onclick = function() {
  if ('FileReader' in window) {
    document.getElementById('file-browser').click();
  } else {
    alert('Your browser does not support the HTML5 FileReader.');
  }
};

document.getElementById('file-browser').onchange = function(event) {
  var fileToLoad = event.target.files[0];

  if (fileToLoad !== undefined) {
    var reader = new FileReader();
    reader.onload = function(fileLoadedEvent) {
      var textFromFileLoaded = fileLoadedEvent.target.result;
      document.getElementById('textarea1').value = textFromFileLoaded;
    };
    reader.readAsText(fileToLoad, "UTF-8");
  }
};

document.getElementById('btn-save').onclick = function() {
  if ('Blob' in window) {
    var fileName = prompt('Please enter file name to save', 'Untitled.txt');
    if (fileName) {
      var textToWrite = document.getElementById('textarea1').value.replace(/\n/g, '\r\n');
      var textFileAsBlob = new Blob([textToWrite], {
        type: 'text/plain'
      });

      if (!!window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
      } else {
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        downloadLink.innerHTML = "Download File";
        if ('webkitURL' in window) {
          // 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();
      }
    }
  } else {
    alert('Your browser does not support the HTML5 Blob.');
  }
};

function...