JSFiddle - React, Tailwind, and code Playground

by dife

HTML

<button id="salvar">Salvar</button>
<input type="file" id="campoSelect" />
<!--<textarea id="showresult"></textarea> !-->


<script src="//cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2014-11-29/FileSaver.min.js"></script>

JavaScript

var openbtn = document.getElementById("campoSelect"),
    saveBtn = document.getElementById("salvar");
    //showout = document.getElementById("showresult");


saveBtn.addEventListener("click", salvar, false);
//função de abrir na tela o arquivo. não utilizada se for só para salvar o arquivo.
//openselect.addEventListener("change", doOpen, false);


// when input type is 'file', it becomes this ....
// reference:
// http://www.javascripture.com/FileReader
//

//função para abrir o arquivo do campo file para mostrar na tela. é desnecessário se quer só baixar o aarquivo.
/*function doOpen(evt) {
    var files = evt.target.files;
    var reader = new FileReader();
    reader.onload = function () {
        showout.value = reader.result;
        var readback = JSON.parse (reader.result);
        console.log (readback);
    };
    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
//

//Função para salvar o arquivo no próprio computador.
function salvar() {
    var filename = prompt("insira o nome do arquivo ", "arquivo.xls");
    var data = {
        temp: 36.5,
        humidity: 85.4
    };
    var string = JSON.stringify (data);
    console.log (string);
    var blob = new Blob([string], {
        type: "text/plain;charset=utf-8"
    });
    
    saveAs(blob, filename);
}