2015-03-31 39 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