2015-03-31 40 views
9

我有一个环回API的模型,我想下载它作为一个文件,而不是显示为文本。我有一些旧的PHP代码,我有混蛋适应尝试和下载响应作为一个文件。从Strongloop环回下载文件

这是我的代码:

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响应为文件的问题。

+1

你的'getCSV'遥控器是什么样的?为什么不把这个代码放在远程方法而不是钩子? – jakerella 2015-03-31 17:36:22

回答

19

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

文件:普通/模型/ 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”,

+0

谢谢。真棒回答。定义响应标题是个诀窍! – Richard 2016-02-05 20:01:17