【问题标题】:Getting downloads to work between angularjs and express.js让下载在 angularjs 和 express.js 之间工作
【发布时间】:2012-12-03 08:37:34
【问题描述】:

我可以获得我请求的文件的原始数据,但我无法让浏览器将文件提供给用户。我需要使用 iframe 吗?

   //Client code
   download_file: function (path, callback) {
       $http.post('/download/client_file', {path:path}).
           success(function(data, status, headers, config) {
                console.log(data); //this contains the raw data of the res.download 
                                   //from the server.
           });
   }

   //server code
   res.download(file); // the path is proper

【问题讨论】:

  • 使用 HTTP GET 会更好吗? (也就是模拟用户点击文件链接时会发生什么)
  • 无论我使用 GET 还是 POST 都没有关系,我只是没有正确的表单数据对象。

标签: download express angularjs


【解决方案1】:

根据文件类型以及文件头的设置方式,您可能会发现从您的 JS 中简单地调用 location.href="uriString"; 会容易得多。文件应该立即下载,使用您已经在其中的窗口。如果它是 JSON 或文本数据,您可能需要调整标题以使其下载而不是呈现内联...(“内容处置:附件”,也许。 ..)

【讨论】:

    【解决方案2】:

    我在我的服务文件中使用了以下代码来下载项目,效果很好。我从http://filamentgroup.com/lab/jquery_plugin_for_requesting_ajax_like_file_downloads/得到它

    $('<form action="'+ url +'" method="'+ ('post') +'">'+inputs+'</form>')
                   .appendTo('body').submit().remove();
    

    【讨论】:

    • 如果可以的话,我会 +2。很棒的解决方案。在这个答案中要澄清的一件事是inputs 可能看起来像这样:&lt;input type="hidden" name="json" value="{{mydata}}" /&gt; 其中mydata 是来自您的$scope 的某个对象。在我的博客上查看我的完整示例:jessemon.blogspot.com/2013/11/…
    • 我遇到了同样的问题 - 我有一个控制器正在对我的主 app.js 执行 $http.put()。我得到的数据响应也是我的 .csv 文件的原始输出,用上面的替换它并没有给我Reference Error: $ is not defined 我有什么遗漏吗?
    • @MonsterWimp757 如果你想使用 $ 检查你是否在 index.html 的角度之前加载了 jquery
    猜你喜欢
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-05
    • 1970-01-01
    • 2016-12-21
    • 2022-07-06
    • 2014-02-20
    相关资源
    最近更新 更多