javascript 使用 angular $http.get 从服务器下载文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29079844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download file from server with angular $http.get
提问by swenedo
I am trying to trigger a file download when a user clicks on a "Download PDF" button. A call is made to the API which makes a few checks, and then returns the file. I don't want the file to open in the browser. I have read a lot of stackoverflow-questions about how to do this, but can't get it to work. I get the file content as text back, but the browser doesn't save the file, nor gives me the choice to save it as a file.
当用户单击“下载 PDF”按钮时,我试图触发文件下载。调用 API 进行一些检查,然后返回文件。我不想在浏览器中打开文件。我已经阅读了很多关于如何执行此操作的 stackoverflow 问题,但无法使其正常工作。我将文件内容作为文本返回,但浏览器不保存文件,也不让我选择将其保存为文件。
This is what I have.
这就是我所拥有的。
HTML
HTML
<button ng-click="apiDownload()">Download PDF</button>
AngularJS controller
AngularJS 控制器
$scope.apiDownload = function(){
var config = {
method: 'GET',
url: "/api/download",
headers: {
'Accept': 'application/pdf'
}
};
$http(config)
.success(function(res){
console.log(res);
})
.error(function(res){});
};
PHP API(mostly from here)
PHP API(主要来自这里)
function apiDownloadFile() {
$file_name = "download/test.pdf";
$abs_file_name = realpath(dirname(__FILE__)).'/'.$file_name;
if(is_file($abs_file_name) && file_exists($abs_file_name)) {
// required for IE
if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); }
// get the file mime type using the file extension
switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
case 'pdf': $mime = 'application/pdf'; break;
case 'zip': $mime = 'application/zip'; break;
case 'jpeg':
case 'jpg': $mime = 'image/jpg'; break;
default: $mime = 'application/force-download';
}
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($abs_file_name)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename='.basename($abs_file_name));
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($abs_file_name)); // provide file size
header('Connection: close');
readfile($abs_file_name); // push it out
exit();
}
}
I see these headers in chrome developer tools:
我在 chrome 开发人员工具中看到这些标题:
Request Headers
请求头
GET /api/download HTTP/1.1
Host: sa.dev
Connection: keep-alive
Cache-Control: no-cache
Pragma: no-cache
Accept: application/pdf
If-Modified-Since: 0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36
Referer: https://sa.dev/insights
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,da;q=0.6,sv;q=0.4,no;q=0.2,nb;q=0.2
Cookie: ...
Response Headers
响应头
HTTP/1.1 200 OK
Date: Mon, 16 Mar 2015 14:27:08 GMT
Server: Apache/2.4.9 (Unix) PHP/5.6.5 OpenSSL/0.9.8zc
X-Powered-By: PHP/5.6.5
Pragma: public
Expires: 0
Cache-Control: must-revalidate, post-check=0, pre-check=0
Last-Modified: Mon, 16 Mar 2015 09:04:06 GMT
Cache-Control: private
Content-Disposition: attachment; filename=test.pdf
Content-Transfer-Encoding: binary
Content-Length: 5501633
Connection: close
Content-Type: application/pdf
采纳答案by swenedo
I solved this by using John Culviner's jQuery.fileDownloadlibrary (see this SO-answer).
我通过使用John Culviner的jQuery.fileDownload库解决了这个问题(参见这个SO-answer)。
When using jQuery.fileDownload I had to do add two things to my code.
使用 jQuery.fileDownload 时,我必须在代码中添加两件事。
Set a cookie
- In PHP:
setcookie('fileDownload', "true", NULL, '/');
- Set-Cookie header will look like this:
Set-Cookie: fileDownload=true; path=/
- In PHP:
Call
$.fileDownload('/api/download');
from js. And remove use of angular $http.
设置一个cookie
- 在 PHP 中:
setcookie('fileDownload', "true", NULL, '/');
- Set-Cookie 标头将如下所示:
Set-Cookie: fileDownload=true; path=/
- 在 PHP 中:
$.fileDownload('/api/download');
从 js调用。并删除使用 angular $http。
See this blogfor more information of how to use jQuery.fileDownload.
有关如何使用 jQuery.fileDownload 的更多信息,请参阅此博客。
If someone have a solution to do this without using a jQuery library, feel free to post it as an answer.
如果有人在不使用 jQuery 库的情况下有解决方案,请随时将其发布为答案。
回答by nix
$scope.apiDownload = function(){
window.open('api/download');
};
Works great
效果很好