【问题标题】:Force browser to download file from node js response强制浏览器从节点 js 响应下载文件
【发布时间】:2017-01-30 06:16:39
【问题描述】:

我正在尝试使用节点 js 从远程 URL 下载文件并将文件发送到浏览器。响应返回到我的前端代码后,我想自动下载它。有人可以帮忙吗?这是我的代码 sn-p:

Backend node js code I am using request to make the remote url call:
  var request = require('request');
  var config = req.param('config');
  res.setHeader("content-disposition", "attachment; filename=" + config.fileName);
  request('http://' + config.hostname + ':' + config.port + config.path).pipe(res);

Front end code in angular 1.5x:
var config = {
          hostname: APP_CONFIG.API_HOST,
          port: APP_CONFIG.API_PORT,
          path: '/document,
          method: 'GET',
          fileName: row.Name,
          fileType: row.Type
        };

        $http.put('/getFileFromUrl', {
          config: config
        })
        .then(function onSuccess(res) {
          if (res.data !== null && res.data.error === undefined) {
            // .........what should I do here its not auto downloading
            if (APP_VARS.isLoader === true) {
              APP_VARS.isLoader = false;
              grxUI.loading.stop();
            }
          }
        })

【问题讨论】:

  • 代码使用$http.put,但配置中的方法是GET。你来这里的目的是什么?获取还是放置?
  • PUT 是路由到节点 js 服务器调用,GET 是实际从远程 URL 获取文件
  • 客户端不能强制服务端
  • 我正在尝试从远程 URL 下载我在节点 js 上读取的文件。我得到响应并将其分块到客户端。一切都很好 - 但是我如何再次将其转换为 BLOB,以便我可以创建一个 A 标记,从 blob 中创建 URL 并调用 a.click() 来下载文件。

标签: angularjs node.js


【解决方案1】:

这是一个下载按钮的示例,该按钮在从服务器加载数据后变为活动状态:

<a download="data_{{files[0].name}}" xd-href="data">
  <button ng-disabled="!data">Download</button>
</a>

xdHref指令

app.module("myApp").directive("xdHref", function() {
  return function linkFn (scope, elem, attrs) {
     scope.$watch(attrs.xdHref, function(newVal) {
       if (newVal) {
         elem.attr("href", newVal);
       }
     });
  };
});

DEMO on PLNKR.


使用 AngularJS 下载二进制文件

下载二进制文件时,设置 XHR 的responseType 属性很重要。

var config = { responseType: 'blob' }

var httpPromise = $http.get(url, config);

httpPromise.then(function (response) {
    $scope.data = response.data;
});

更多信息请见MDN XHR API - ResponseType.

【讨论】:

  • 感谢您的快速回复 - 它在 PDF 上失败。
  • 事实上,我尝试了其他文件类型,如 xls、doc 等 - 他们都失败了。你能看一下吗?
  • 请看我上面对@akinjide 的评论
猜你喜欢
  • 2011-09-25
  • 2013-07-05
  • 1970-01-01
  • 2017-10-29
  • 2010-12-27
  • 2018-05-15
  • 2015-04-16
  • 1970-01-01
  • 2017-11-04
相关资源
最近更新 更多