【问题标题】:How to download a file sent by php readfile(), triggered by AngularJs $http get如何下载由 AngularJs $http get 触发的 php readfile() 发送的文件
【发布时间】:2013-10-06 19:02:33
【问题描述】:

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

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

我怎样才能允许用户将此数据下载为文件?

【问题讨论】:

  • 一方面header("Content-Disposition: attachment; filename=\".basename($fileLocation)\""); 不正确。它只会读取.basename($fileLocation) 的文字字符串,因为您在那里缺少"。看看您发布的代码中突出显示的语法。
  • 根据您的评论固定来源 - 谢谢,但行为没有改变。

标签: javascript php angularjs download


【解决方案1】:

我推荐以下内容,进一步描述here

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2023-03-18
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多