Home > Software engineering >  How to generate a download file in javascript
How to generate a download file in javascript

Time:06-11

I was stuck here not understood go further. some screens works same code but some not.

var element = document.createElement('a'); 
          element.setAttribute('href', 'data:text/html;charset=utf-8,'   encodeURIComponent(strOutput.replaceAll('£', '£'))); 
          element.setAttribute('download',"fpversions"); 
          element.style.display = 'none'; 
          document.body.appendChild(element); 
          element.click(); 
          document.body.removeChild(element);

can anyone help me.

CodePudding user response:

this is a sample javascript code on how to download files via javascript

  var textToSave = 'this is a test';
  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:attachment/text,'   encodeURI(textToSave);
  hiddenElement.target = '_blank';
  hiddenElement.download = 'myFile.txt';
  hiddenElement.click();

function myFunction() {
  var textToSave = 'this is a test';
  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:attachment/text,'   encodeURI(textToSave);
  hiddenElement.target = '_blank';
  hiddenElement.download = 'myFile.txt';
  hiddenElement.click();
}
<button onclick="myFunction()">Click me</button>

  • Related