Latest Posts

Monday, April 6, 2015

File Download using Java Script


<script>
        function saveTextAsFile() {
            var textToWrite = document.getElementById("inputTextToSave").value;
            var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' });
            var fileNameToSaveAs = "myNewFile.txt";
            var downloadLink = document.createElement("a");
            downloadLink.download = fileNameToSaveAs;
            downloadLink.innerHTML = "My Hidden Link";
            window.URL = window.URL || window.webkitURL;
            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);
        }
    </script>
</head>
<body>
    <textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
    <button onclick="saveTextAsFile()">Save Text to File</button>
</body>