Problem:
How to load, edit and save a text file in HTML5 using JavaScript?
How to read and write files in JavaScript?
How to upload, edit and download a file in HTML5 using JavaScript?
Solution:
Some features of HTML5 to allow the user to load, edit, and save a text file on their local computer. So, user can use HTML5 and JavaScript to upload, edit and download/save file. To better understand please see the bellow example.
Example:
<html>
<head>
<style>
#panelShowTable
{float:left; width:700px; height:600px; margin:10px;padding:10px;border:1px solid #aaaaaa;}
#panelHiddenTable
{float:left; width:600px; height:600px; margin:10px;padding:10px;border:1px solid #aaaaaa;}
#panelDataShow
{display:inline-block;}
#button4Save
{float:right;}
#button4Load
{float:right;}
</style>
<script type='text/javascript'>
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
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();
}
function destroyClickedElement(event)
{
document.body.removeChild(event.target);
}
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
</head>
<body>
<div id="panelShowTable">
<div id="panelShowTableHader">
<h3>Text to Save:</h3>
</div>
<div id="panelShowTableTextarea">
<textarea id="inputTextToSave" style="width:700px;height:500px"></textarea>
</div>
<div id="panelShowTableFile" >
<b>Filename to Save As:</b>
<input id="inputFileNameToSaveAs" autofocus>
<button id="button4Save" onclick="saveTextAsFile();">Save Text to File</button>
</div>
<div>
<b>Select a File to Load:</b>
<input type="file" id="fileToLoad">
<button id="button4Load" onclick="loadFileAsText()">Load Selected File</button>
</div>
</div>
</body>
</html>
Suggestion:
If you have better solution for this questions please don't hesitate to give a comment bellow.Thank you.