Download Files Using Javascripts for Different Types of Browser

  1. $scope.downloadDocument = function()  
  2. {  
  3.     // Here we are passing URL from where we are going to download file to browser  
  4.     var documentUrl =  
  5.     {  
  6.         'FileName': $scope.selectedRow[0].Url  
  7.     };  
  8.     // following  method will give call to javascript method  
  9.     Download($scope.selectedRow[0].Url)  
  10. };  
  11.   
  12. function Download(url)  
  13. {  
  14.     // Here we identifying browser   
  15.     var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;  
  16.   
  17.     var isFirefox = typeof InstallTrigger !== 'undefined';  
  18.   
  19.     var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;  
  20.   
  21.     var isChrome = !!window.chrome && !isOpera;  
  22.   
  23.     var isIE = /*@cc_on!@*/ false || !!document.documentMode;  
  24.   
  25.     if (isChrome || isFirefox)   
  26.     {  
  27.         var save = document.createElement('a');  
  28.         save.href = url;  
  29.         save.target = '_blank';  
  30.         save.download = $scope.selectedRows[0].Name;  
  31.         var evt = document.createEvent('MouseEvents');  
  32.         evt.initMouseEvent('click'truetrue, window, 1, 0, 0, 0, 0,  
  33.             falsefalsefalsefalse, 0, null);  
  34.         save.dispatchEvent(evt);  
  35.         (window.URL || window.webkitURL).revokeObjectURL(save.href);  
  36.     }  
  37.     if (isIE) {  
  38.         // Force downloading of pdf files (it will NEVER allow any browser specific pdf-reader to render/open your pdf files):                              var _window = window.open(fileURL, '_blank');  
  39.   
  40.         //  To force downloading pdf uncomment following line of code and comment above line  
  41.         //  var _window = window.open(url, '', 'left=10000,screenX=10000')  
  42.         _window.document.close();  
  43.         _window.document.execCommand('SaveAs'null, url)  
  44.         _window.close();  
  45.     }  
  46. };