【问题标题】:Offer file download提供文件下载
【发布时间】:2014-12-20 11:43:07
【问题描述】:

我目前正在开发一个使用 PHP 编写的服务器后端的 AngularJS 项目。前端和后端完全使用 JSON 进行通信,但是,在导出场景中,服务器的输出不是 JSON 编码的,而是一个(文本或二进制)文件。

Web 应用程序不能仅仅将客户端的浏览器重定向到下载 URL,因为服务器需要 HTTP 请求中的自定义标头(即 API 密钥)来提供文件。因此,我在 AngularJS 中使用 $http 来发起 AJAX 请求。这是发生了什么:

在服务器端生成文件(使用带有 Slim 框架的 PHP):

$export = $this->model->export_cards($project_key);

$this->app->response()->status(200);
$this->app->response()->header("Content-Type", "text/plain");
$this->app->response()->header("Content-Disposition", "attachment; filename=\"export.txt\"");
$this->app->response()->header("Last-Modified", date("r");
$this->app->response()->header("Cache-Control", "cache, must-revalidate");
$this->app->response()->body($export);

$this->app->stop();

这是客户端发生的事情(到目前为止):

$http({
    method:     "get",
    url:        "/server/projects/cards/export_cards/" + $scope.key,
    headers:    {
        "X-API-Key":    session_service.get("api_key")
    }
}).then(
    function(response)
    {
        // Success, data received

        var data = response.data; // This variable contains the file contents (might be plain text, or even binary)

        // How do I get the browser to offer a file download dialog here?
    },
    function(response)
    {
        // Error handling
    }
);

我在 AngularJS 前端成功接收文件内容并将它们存储在变量 data 中。如何让浏览器显示文件下载对话框?

该解决方案必须在 Internet Explorer 10+ 和相当新的 Firefox、Chrome 和 Safari 版本(仅限桌面版本)中运行。

实现这一目标的最佳方法是什么?

感谢您的帮助,如果我需要提供任何其他信息,请告诉我。

彼得

【问题讨论】:

标签: php angularjs slim


【解决方案1】:

我不确定这是否可行。

您可以:

直接提供API密钥,例如:

location.href = "/server/projects/cards/export_cards/" + $scope.key + '?api_key=' + session_service.get("api_key");

或者,让您的 API 为文件下载返回一个临时的、过期的 URL,然后使用 location.href 访问此 URL。

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 2013-03-25
    • 1970-01-01
    • 2017-10-09
    • 2012-06-21
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多