JSFiddle - React, Tailwind, and code Playground

by Brunno Romero

HTML

<input type="text" id="inputFileNameToSaveAs" placeholder="nome do arquivo" />
<br>
<br>
<textarea id="inputTextToSave"></textarea>
<input id="inputTextBtn" type="button" value="gerar" />

JavaScript

document.getElementById('inputTextBtn').onclick = saveTextAsFile;

function saveTextAsFile() {

    var textToWrite = document.getElementById("inputTextToSave").value;

    if(textToWrite == '') {
        alert('textarea vazia :´/');
        return;
    }

    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.style.display = "none";
        document.body.appendChild(downloadLink);

    }

    downloadLink.click();

    setTimeout(function () {
        alert('arquivo baixado com sucesso!')
    }, 2000);
}

function destroyClickedElement(event) {
    alert('foi clicado para baixar =DD');
    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");
}