Generate file with JS [duplicate]

0

I have a query and I put a string with the result. Until then everything is ok!

What is working for me is to find a good way so that when the query finishes and the string is already set up, a file containing the string is downloaded to the client's pc.

    
asked by anonymous 11.06.2018 / 20:07

1 answer

4

You can define an anchor element, <a> , using URL encoding to generate your TXT file and download it. You only need to dynamically create the element, set the href attribute and the download property to the name of the file you want to create; after you insert it into the body of the page - some browsers can block the click event if the element is not in the body of the page - and trigger the click event of the element, removing it from the body of the page at the end. >

function createAndDownload(filename, text) {
  const element = document.createElement('a');

  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

See an example:

function createAndDownload(filename, text) {
  const element = document.createElement('a');

  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}
<button onClick="createAndDownload('sopt.txt', 'Stack Overflow em Português')">Download</button>
    
11.06.2018 / 20:16