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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With