Function that generates file

2

How to create a function in javascript that generates an .ini file?

For example, I will fill 2 fields and it will generate a file like this

[teste]
nome: "campo 1 que vou preencher"
teste: teste
teste: teste
email: "campo 2 que vou preencher"
teste: teste
teste:

That's it, then the person clicks Save or Download and downloads the file I'm trying to use FileSaver, but I'm having trouble even running the demo of it.

I tried it in a similar way, more or less like this

$('#salvar').click(function() {
    var nome = $('#nome').val();
    var email = $('#email').val();
    this.href = "data:text/plain;charset=UTF-8," + encodeURIComponent(texto);
});
    
asked by anonymous 13.09.2016 / 20:36

2 answers

4

A different approach would be to create a blob with the values. After that, just download.

An example usage would look like this:

function baixarArquivo() {
  var nome = document.getElementById('nome').value;
  var email = document.getElementById('email').value;

  var texto = '[teste]\n' +
    'nome: ' + nome + '\n' +
    'teste: teste\n' +
    'teste: teste\n' +
    'email: ' + email + '\n' +
    'teste: teste\n' +
    'teste:';

  var fileName = 'arquivo.txt';
  var fileContent = texto;

  var arquivo = new Blob([fileContent], {
    type: 'text/plain'
  });

  window.URL = window.URL || window.webkitURL;
  document.getElementById('download').setAttribute('href', window.URL.createObjectURL(arquivo));
  document.getElementById('download').setAttribute('download', fileName);
}
Nome: <input id="nome" />
<br/>
E-mai: <input id="email" />
<br/>
<a href="" id="download" onclick="baixarArquivo();">Download</a>

Remembering that you can change the extension in the file name.

Reference

    
13.09.2016 / 21:05
4

function download(filename, nome, email) {
  var element = document.createElement('a')
  element['href'] = 'data:text/plain;charset=utf-8,' + encodeURIComponent(nome + '\n' + email)
  element['download'] = filename

  element['style']['display'] = 'none'
  document['body']['appendChild'](element)

  element['click']()

  document['body']['removeChild'](element)
}
form * {
  display: block;
  margin: 10px;
}
<form onsubmit="download(this['arquivo'].value, this['nome'].value, this['email'].value)">
  <input type="text" id="arquivo" value="teste.txt">
  <input type="text" id="nome" name="Nome">
  <input type="text" id="email" name="E-Mail">	    
  <input type="submit" value="Download">
</form>

Source: link

    
13.09.2016 / 20:52