Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file sent by php readfile(), triggered by AngularJs $http get

I have an angularJs application making calls to a PHP server. In this situation, an AngularJS service is called to make an $http.get call to the PHP server. At the end of the PHP's function work, it sends some data using a readFile function.

PHP response:

header('Content-Description: File Transfer');
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".basename($fileLocation)."\"");
header("Content-Transfer-Encoding: binary");
header("Expires: 0");//            header('Content-Disposition: attachment; 
header("Pragma: public");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Length: ' . filesize($fileLocation)); //Remove

flush();
readfile($fileLocation);

The file data IS successfully retrieved by the browser - its being returned as the result of the $http.get promise.

Angular Function Call and Promise Result

app.controller('ControllerName', function($scope,myService){
    $scope.downloadFile = function(){
        var getFile = myService.GetFile();
        getFile.success(function(result){
            // result here DOES contain the file contents! 
            // so... how to allow user to download??
        });
        getFile.error(function(result){
            $scope.message = result.error;
        });
    };
});

How can I allow the user to download this data as a file?

like image 969
Spaajanen Avatar asked Jan 20 '26 21:01

Spaajanen


1 Answers

I recommend the following which is further described here.

var pom = document.createElement('a'); 
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); 
pom.setAttribute('download', filename); 
pom.click()
like image 159
Paul D. Eden Avatar answered Jan 22 '26 11:01

Paul D. Eden