如何下载由 php readfile() 发送的文件,由 AngularJs 触发$http获取


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

我有一个angularJs应用程序调用PHP服务器。在这种情况下,调用 AngularJS 服务来对 PHP 服务器进行 $http.get 调用。在 PHP 的函数工作结束时,它使用 readFile 函数发送一些数据。

PHP响应:

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);

浏览器成功检索了文件数据 - 它是作为 $http.get 承诺的结果返回的。

角度函数调用和承诺结果

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;
        });
    };
});

如何允许用户将此数据下载为文件?

我推荐以下内容,此处将进一步描述。

var pom = document.createElement('a'); 
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); 
pom.setAttribute('download', filename); 
pom.click()