简体   繁体   中英

Not able to download valid zip file using angularjs, however on directly hitting my rest api it is working

Below is my angular.js code

App.factory('JobMigrationService', ['$http','$q',function($http, $q) {

return {
    downloadSvc: function(requestPayload) {
        console.info(requestPayload);
        return $http.get('http://localhost:8080/XXXX',{params:{"params":value}},{responseType:'arraybuffer'})
        .then(
                function(response){
                    console.info(response);
                    var a = document.createElement('a');
                    var blob = new Blob([success], {'type':"application/octet-stream",'responseType':"arraybuffer"});
                    a.href = URL.createObjectURL(blob);
                    a.download = "filename.zip";
                    a.click();
                }, 
                function(errResponse){
                    console.error('Error');
                    return $q.reject(errResponse);
                }
        );
    }
}

}]);

Download is happening but when try to open the zip file it says it is invalid however using the rest api direct hit it is working fine.

Thanks in advance

I think this must be it

  var blob = new Blob([success], {'type':"application/octet-stream",'responseType':"arraybuffer"});

Whats [success] ? shouldnt it be

   var blob = new Blob(response.data, {'type':"application/octet-stream",'responseType':"arraybuffer"});

This is a bit cleaner. I think

    App.factory('JobMigrationService', ['$http','$q',function($http, $q) {

return {
    downloadSvc: function(requestPayload) {
        console.info(requestPayload);
        return $http.get('http://localhost:8080/XXXX',{params:{"params":value}},{responseType:'blob'})
        .then(
                function(response){
                    console.info(response);
                    var a = document.createElement('a');
                    a.href = URL.createObjectURL(response.data);
                    a.download = "filename.zip";
                    a.click();
                }, 
                function(errResponse){
                    console.error('Error');
                    return $q.reject(errResponse);
                }
        );
    }
}

}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM