从Strongloop环回下载文件

Ste*_*v_k 11 node.js loopbackjs

我在loopback 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();
});
Run Code Online (Sandbox Code Playgroud)

我见过有关使用环回下载现有文件的问题,但从未将REST响应作为文件下载.

Sim*_*kir 24

根据你的方法,它就像这样工作.在我的情况下,'组织'是模型.

文件: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.
};
Run Code Online (Sandbox Code Playgroud)

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

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

虽然type只是不同CSV文件导出的get参数..

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