3

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?

Spaajanen
  • 383
  • 6
  • 15
  • For one thing `header("Content-Disposition: attachment; filename=\".basename($fileLocation)\"");` is incorrect. It's just going to be reading the literal string of `.basename($fileLocation)` since you're missing a `"` there. Take a look at the syntax highlighting in the code you posted. – ChicagoRedSox Sep 30 '13 at 19:40
  • fixed source as per your comment - thanks, but no change in behaviour. – Spaajanen Sep 30 '13 at 20:50

1 Answers1

2

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()
Community
  • 1
  • 1
Paul D. Eden
  • 19,939
  • 18
  • 59
  • 63