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)
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",
| 归档时间: |
|
| 查看次数: |
7672 次 |
| 最近记录: |