我有一个 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/