how to download a file with js code example

Example 1: javascript write to file and download

function download(filename, text) {
  var 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);
}

// Start file download.
download("hello.txt","This is the content of my file :)");

Example 2: javascript download file

$('a#someID').attr({target: '_blank', 
                    href  : 'http://localhost/directory/file.pdf'});

Example 3: js download file from webserver

<iframe id="download_iframe" style="display:none;"></iframe>
<script>
	document.getElementById('download_iframe').src = "/example/example.txt";
</script>

Example 4: how to set a var in js to be a download

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();

Tags:

Java Example