Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Download binary file in angular js using http

Tags:

angularjs

I want to downlaod exe file using $http, it shows me when I console the data, but I am unable to download it.

$http({
        url: url,
        method: "GET",
        headers: {
           'Content-type': 'application/json'
        }
    }).success(function (data, status, headers, config) {
        console.log(data);

        window.open(objectUrl);
    }).error(function (data, status, headers, config) {
        //upload failed
    });

Any help would be appreciated.

like image 619
Abdul Majeed Avatar asked Mar 13 '23 11:03

Abdul Majeed


2 Answers

you can Use response type like responseType: "arraybuffer"

$http({
    url: url,
    method: "GET",
    headers: {
       'Content-type': 'application/json'
    },
  responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
    console.log(data);
   var file = new Blob([data], { type: 'application/binary' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
var link=document.createElement('a');
link.href=fileURL;
link.download="testing.exe";
link.click();
    window.open(objectUrl);
}).error(function (data, status, headers, config) {
    //upload failed
});

and use Blob and pass type "application/binary" and create a link to download it.

like image 141
SamiMalik Avatar answered Mar 23 '23 09:03

SamiMalik


Given code will help you to download exe file as well as to check browser compatibility.

var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g); 

var blob = new window.Blob([data.data], { type: 'application/x-msdownload' });

if (ie || oldIE || ieEDGE) {

    var fileName="filename"+'.exe';
    window.navigator.msSaveBlob(blob, fileName);
}
else {

    var file = new Blob([ data.data ], {
        type : 'application/x-msdownload'
    });

    var fileURL = URL.createObjectURL(file);
    var a         = document.createElement('a');
    a.href        = fileURL; 
    a.target      = '_blank';
    a.download    = "filename"+'.exe';
    document.body.appendChild(a);

    a.click();

}
//Successfully Downloaded
like image 22
Riddhi Gohil Avatar answered Mar 23 '23 10:03

Riddhi Gohil