FileReader & Save
by jmchen
HTML
<button id="save">save</button>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>
<hr>
<p>HTML tags: button, input, and (optionally) a textarea</p>
<p>JavaScript: <a href='https://developer.mozilla.org/en-US/docs/Web/API/Blob'>FileReader</a>, <a href='https://github.com/eligrey/FileSaver.js/'>FileSaver</a>
<script src="//cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
CSS
#save {
background: pink;
}
#openselect {
background:yellow;
}
#showresult {
width:98%;
height: 300px;
background:cyan;
}
JavaScript
var openbtn = document.getElementById("openselect"),
saveBtn = document.getElementById("save"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
saveBtn.addEventListener("click", doSave, false);
// when input type is 'file', it becomes this ....
function doOpen(evt) {
var files = evt.target.files;
var reader = new FileReader();
reader.onload = function () {
showout.value = this.result;
// alert(this.result);
};
//reader.readAsText(files[0]);
// https://developer.mozilla.org/en-US/docs/Web/API/Blob
// start reading contents of the Blob,
// once finished, the 'result' contains the content
// of the file as a text string
}
//
// prompt reference:
// http://www.w3schools.com/jsref/met_win_prompt.asp
//
//
// Blob reference:
// https://developer.mozilla.org/en-US/docs/Web/API/Blob
//
function doSave() {
var filename = prompt("File? ", "data.txt");
var string = "a b c d e";
var blob = new Blob([string], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, filename);
}