【问题标题】:Downloading file from Strongloop loopback从 Strongloop 环回下载文件
【发布时间】:2015-03-31 15:31:17
【问题描述】:

我在环回 API 中有一个模型,我想将其作为文件下载而不是显示为文本。我有一些旧的 PHP 代码 bastardized 适合尝试将响应下载为文件。

这是我的代码:

Issue.afterRemote('getCSV', function(ctx, affectedModelInstance, next) {
var result = ctx.result;
console.log(result);
var currentdate = new Date(); 
var datetime = currentdate.getDate() + " " +
            + (currentdate.getMonth()+1) + " " +
            + currentdate.getFullYear() + " " +
            + currentdate.getHours() + ":"  
            + currentdate.getMinutes() + ":" 
            + currentdate.getSeconds(); + " ";
ctx.res.set('Expires', 'Tue, 03 Jul 2001 06:00:00 GMT');
ctx.res.set('Cache-Control', 'max-age=0, no-cache, must-revalidate, proxy-revalidate');
ctx.res.set('Last-Modified', datetime +'GMT');
// force download  
ctx.res.set('Content-Type','application/force-download');
ctx.res.set('Content-Type','application/octet-stream');
ctx.res.set('Content-Type','application/download');
// disposition / encoding on response body
ctx.res.set('Content-Disposition','attachment;filename=Data.csv');
ctx.res.set('Content-Transfer-Encoding','binary');
ctx.res.send(result);

}, function(err, response) {
if (err) console.error(err);
//    next();
});

我看到了有关下载 existing files with loopback 的问题,但从未将 REST 响应下载为文件。

【问题讨论】:

  • 您的getCSV 遥控器是什么样的?为什么不把这段代码放在那个远程方法中而不是作为一个钩子呢?

标签: node.js loopbackjs


【解决方案1】:

根据您的方法,它的工作原理是这样的。在我的例子中,“组织”就是模型。

文件:common/models/organisation.js

Organisation.csvexport = function(type, res, callback) {
  //@todo: get your data from database etc...
  var datetime = new Date();
  res.set('Expires', 'Tue, 03 Jul 2001 06:00:00 GMT');
  res.set('Cache-Control', 'max-age=0, no-cache, must-revalidate, proxy-revalidate');
  res.set('Last-Modified', datetime +'GMT');
  res.set('Content-Type','application/force-download');
  res.set('Content-Type','application/octet-stream');
  res.set('Content-Type','application/download');
  res.set('Content-Disposition','attachment;filename=Data.csv');
  res.set('Content-Transfer-Encoding','binary');
  res.send('ok;'); //@todo: insert your CSV data here.
};

以及远程方法定义(获取响应对象)

Organisation.remoteMethod('csvexport',
{
  accepts: [
    {arg: 'type', type: 'string', required: true },
    {arg: 'res', type: 'object', 'http': {source: 'res'}}
  ],
  returns: {},
  http: {path: '/csvexport/:type', verb: 'get'}
});

虽然类型只是不同 CSV 文件导出的获取参数..

注意:我使用的是“loopback”:“^2.10.2”,

【讨论】:

  • 谢谢。很棒的答案。定义响应头是诀窍!
  • 想知道什么是 res?你如何将它传递给 Organisation.csvexport?
  • res 为 express 响应对象,由 strongloop 自动提供。
猜你喜欢
  • 2016-07-04
  • 1970-01-01
  • 2015-09-18
  • 2012-12-18
  • 2014-12-14
  • 1970-01-01
  • 2015-08-12
  • 2015-07-29
  • 2013-09-10
相关资源
最近更新 更多