javascript - 如何下载由 AngularJs $http get 触发的 php readfile() 发送的文件

标签 javascript php angularjs download

我有一个 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 promise 的结果返回。

Angular 函数调用和 Promise 结果

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

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

最佳答案

我推荐以下进一步描述的here .

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

关于javascript - 如何下载由 AngularJs $http get 触发的 php readfile() 发送的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19102303/

相关文章:

javascript - 我怎样才能等待一个条件?

javascript - 错误 : Module "html" does not provide a view engine (Express)

javascript - 如何从json数据中删除双引号

javascript - 坚持使用简单的 Javascript 函数来查找高度

php - 以表格形式请求许可证

javascript - AngularJS 应用程序中的 Protractor 和 ng-repeat

javascript - jQuery 鼠标悬停连续幻灯片循环

php - 在 PHP 中,如何向从 iPhone InApp 收据检索到的购买日期添加 3 个月?

php - 使用 php 将来自 Twitter API 的数据插入 MySQL 数据库

angularjs - Protractor 与 IDE 集成