Monthly Archives: August 2018

javascript – download Blob file directly

As we know that for security issue, browser would disable javascript to download file directly.

but today what I want to show is to use javascript to click on ‘a’ link to download file
using Blob

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
  if (navigator.msSaveBlob) { // IE 10+
    navigator.msSaveBlob(blob, filename);
  } else {
    var link = document.createElement("a");
    if (link.download !== undefined) { 
      var url = URL.createObjectURL(blob);
      link.setAttribute("href", url);
      link.setAttribute("download", filename);
      link.style.visibility = 'hidden';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }