Friday 4 May 2018

Saving File in javascript without making Server call in muiltiple Browsers(IE,Edge,Chrome,Firefox,Opera and Safari)

Saving File in javascript without making Server call

We can make a file and download to user machine without making a server call in javascript. The trick is to make a anchor tag and write a data in a url which is passed to href.But, this trick doesn't work for Internet Explorer and Edge. We can do that in IE and Edge also with the help of making a blob object and with msSaveOrOpenBlob method.

Following is the code which can be used to do the same:

var data="Hello,This is javascript";
var fileName="download.txt";
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      var blob = new Blob([data], { type: 'text/csv' });
    var done=window.navigator.msSaveOrOpenBlob(blob, fileName);
    }else{
    var element =document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
    element.setAttribute('download', fileName);
 
    element.style.display = 'none';
    document.body.appendChild(element);
 
    element.click();
 
    document.body.removeChild(element);
      }


We can use the same code for downloading the png, csv and other types of files.

There are other methods also but check that it will work on all browser or not.

Labels: ,