Save contents of a variable to a file . txt without saving the file just allow download

Asked

Viewed 39 times

-2

It would take data from an ex variable:

let texto = "Exemplo de Texto"

and create a button that takes this variable and generates a download option, in txt format.

1 answer

-1


You can use the class Blob:

function DownloadArquivo() {
  var data = new Blob(["Exemplo de Texto"]);

  var downloadLink = document.getElementById("aDownloadTxt");
  if (downloadLink == null) {
    downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'arquivo.txt');
    downloadLink.setAttribute('id', 'aDownloadTxt');
    document.body.appendChild(downloadLink);
  }

  downloadLink.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
  downloadLink.href = URL.createObjectURL(data);

  downloadLink.style.display = 'none';
  downloadLink.click();
}
<html>

<head>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <button onclick="DownloadArquivo()">Download</button>
</body>

</html>

  • 1

    Served too much, thank you if you want to call later on Discord Tux(Gabriel Porfiro)#3634. thanks

  • 2

    Enzo, when the operation of the code is limited by the security restrictions of the snippet it is best to leave it as non-executable and provide a link to a sandbox where it can be executed, informing of the limitations here of the page.

Browser other questions tagged

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