Generate file with JS

Asked

Viewed 50 times

0

I have a query and mount a string with the result. So far everything is ok!

What is giving me trouble is to find a good way so that when the query is finished and the string is already mounted, a file containing the string is downloaded to the client’s pc.

  • This might help you if you know English in this case: https://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery

1 answer

4


You can define an anchor element, <a>, using the URL encoding to generate your TXT file and download it. Just create the element dynamically, set the attribute href and the property download with the name of the file you want to create; after you insert it into the body of the page - some browsers may block the event click if the element is not in the body of the page - and trigger the event click of the element by 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);
}

Take 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>

  • Just for display=One with click sometimes does not roll (depends on browser+device), including I proposed a solution with setTimeout and a few more things for compatibility and a series of tests: https://answall.com/a/217960/3635

  • @Would Guillhermenascimento know which does not work? I remember that when I wrote the answer the only limiting was that he needed to add to DOM the anchor to be able to execute the click.

  • It’s something that varies from version to version, which probably today most already suit well the simplest solution, yet I’m always sismado with Vices, as mobiles (of course iOS is the only one that does not have support for this, I do not know how this in iOS12Preview), on iOS11 need to test calmly, today has the native app "Files", but I do not know if it interacts with Safari. I promise to test calmly and return a feedback :)

Browser other questions tagged

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