Save contents of a Textarea to a file . txt and display them again when updating the page

Asked

Viewed 379 times

-1

I’m finishing a HTML to assist me in the tasks of my service, in one of the sessions, I intend to make several "Quick Note Blocks", where I enter a short text and this will be saved in a file txt. But when updating the page, I need this Textarea to return the values saved in txt.

There is the possibility to use only Javascript in this solution? I want to consume as few resources as possible on this page.

Follow an excerpt of the code (I’m using Templates Bootstrap to speed up the process)

<div class="panel-body">
    <textarea class="form-control" id="exampleFormControlTextarea1" rows="5"> 
    </textarea>
</div>
<div class="panel-footer">
   <button type="button" class="btn btn-info btn-circle"><i class="fa fa-check"> 
    </i></button>
   <button type="button" class="btn btn-warning btn-circle"><i class="fa fa-times"></i></button>
</div>

I’m a little inexperienced in the area, I appreciate the help.

  • where will save this txt file?

  • You can even generate a TXT file with Javascript and save it on the client’s machine, but you won’t be able to recover it later. Javascript cannot access the files directly - except for Node. As you do not want to use another language, search about localStorage.

1 answer

0


a solution to your problem is using the localStorage the javascript itself and also use the firestorage google. I made a small example without much deepening in that link. Below is the code used.

index.html

<script src="https://www.gstatic.com/firebasejs/5.5.2/firebase.js"></script>

<input placeholder="Título" id="title" type="text">

<textarea></textarea>

<input id="save" type="button" value='Salvar'>

<input id="download" type="button" value='Baixar'>

index js.

let titleElement = document.querySelector('#title') //Pega o elemento de título
let title        = localStorage.getItem("title") //Recupera o título salvo no localStorage
let textElement  = document.querySelector('textarea') //Pega o elemento de texto
let text         = localStorage.getItem("text") //Recupera o conteudo salvo no localStorage
let btnSave      = document.querySelector('#save') // Pega o botão de salvar
let btnDownload  = document.querySelector("#download") //Pega o botão de download
let firestorage  = null // Armazena o firestorage

//Chama a função initFirestorage
initFirestorage()

//Chama a função bindValueToFields
bindValueToFields()

//Aguarda por um click no botão de salvar
btnSave.addEventListener('click', event => {

  title = titleElement.value.trim() //Pega o conteudo do título
  text = textElement.value.trim() //Pega o conteudo do texto

  localStorage.setItem("title",title)
  localStorage.setItem("text",text)

  //Verifica se título e conteudo estão preenchidos
  if(!text || !title){
    alert("Título e texto devem ser preenchidos")
    return
  }

  //Chama a função upload
  uploadFile(text, title+'.txt', "text/plain;charset=utf-8");

})

/*
 * Função responsável por criar um arquivo e fazer upload
 * no firestorage. Requer o conteudo, nome e mimeType do arquivo.
 * È preciso ter uma conta no firebase para isso, acesse esses links:
 * https://firebase.google.com/docs/storage/web/start?hl=pt-br
 * https://firebase.google.com/docs/web/setup?hl=pt-br
 */
function uploadFile(data, filename, type) {

  return

  //Cria um novo arquivo
  let file = new Blob([data], {type: type});

  /*
   * Após ter criado a conta no firebase é só
   * fazer o upload do arquivo como no exemplo da documentação
   * https://firebase.google.com/docs/storage/web/upload-files?hl=pt-br
   */
  let storageRef = firestorage.ref();
  let ref        = storageRef.child(filename);
  ref.put(file).then(function(snapshot) {
    //O arquivo foi salvo com sucesso
  }).catch(function(err){
    //Ocorreu um erro
  });

}

//Inicializa o Firestorage com as informações da sua conta
function initFirestorage(){

    // Set the configuration for your app
  // TODO: Replace with your project's config object
  var config = {
    apiKey: '<your-api-key>',
    authDomain: '<your-auth-domain>',
    databaseURL: '<your-database-url>',
    storageBucket: '<your-storage-bucket>'
  };
  firebase.initializeApp(config);

  // Get a reference to the storage service, which is used to create references in your storage bucket
  firestorage = firebase.storage();

}

//Recupera os valores anteriores que estão recuperados no localStorage
function bindValueToFields(){

  titleElement.value = title
  textElement.value = text

}

/*
 * Função responsável por fazer o download do arquivo
 * para baixar um arquivo basta digitar o nome do arquivo
 * sem a extensão, no campo título.
 * Exemplo de como baixar o arquivo na documentação:
 * https://firebase.google.com/docs/storage/web/download-files?hl=pt-br
 */
function downloadFile(){

  let storageRef = firestorage.ref();

  storageRef.child(title).getDownloadURL().then(function(url) {

      var xhr = new XMLHttpRequest();
      xhr.responseType = 'blob';
      xhr.onload = function(event) {
        download(xhr.response, title+".text", "text/plain;charset=utf-8")
      };
      xhr.open('GET', url);
      xhr.send();

  })

}

//Faz o download do arquivo
function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

I hope these codes solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.