Create "Download" Link

“Download” link can be generated by HTML5 “a” tag with “download” attribute OR JavaScript code.

HTML5

<a href="./sample.txt" download="SAMPLE">Download</a>

This should work in most of modern browsers except IE. JavaScript code can replace this on these exceptions.

JavaScript

The file to download is saved in memory first with XMLHttpRequest and then saved as a file with URL.createObjectURL. (msSaveBlob in IE/Edge)

JavaScript Code

function downloadFile(url, filename) {

  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = function (oEvent) {
    var blob = xhr.response;
    if (window.navigator.msSaveBlob) {
      // IE/Edge
      window.navigator.msSaveBlob(blob, filename);
    }
    else {
      var objectURL = window.URL.createObjectURL(blob);
      var link = document.createElement("a");
      document.body.appendChild(link);
      link.href = objectURL;
      link.download = filename;
      link.click();
      document.body.removeChild(link);
    }
  };
  xhr.send();
}

HTML

<a href="./sample.txt" download="SAMPLE"
   onclick="javascript: downloadFile('./sample.txt', 'sample.txt'); return false;"
   >Download</a>