Monday, July 25, 2016

save a custom text file in your computer using javascript

Write the text and click.. that's it... your text will be exported into text file in your computer.

Uses-: copy it into an .html file and open that file in a web browser that runs JavaScrip.


So, Here the code-


<html>
<body>

<table>
<tr><td>Text to Save:</td></tr>
<tr>
        <td colspan="3">
            <textarea cols="80" id="inputTextToSave" rows="25"></textarea>
        </td>
    </tr>
<tr>
        <td>Filename to Save As:</td>
        <td><input id="inputFileNameToSaveAs" /></td>
        <td><button onclick="saveTextAsFile()">Save Text to File</button></td>
    </tr>
<tr>
        <td>Select a File to Load:</td>
        <td><input id="fileToLoad" type="file" /></td>
        <td><button onclick="loadFileAsText()">Load Selected File</button><td>
    </td></td></tr>
</table>
<script type="text/javascript">

function saveTextAsFile()
{
    var textToSave = document.getElementById("inputTextToSave").value;
    var textToSaveAsBlob = new Blob([textToSave], {type:"text/plain"});
    var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
    var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;

    var downloadLink = document.createElement("a");
    downloadLink.download = fileNameToSaveAs;
    downloadLink.innerHTML = "Download File";
    downloadLink.href = textToSaveAsURL;
    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>

</body>
</html>

No comments:

Post a Comment