I have a model in the loopback API and I want to download it as a file rather than display it as text. I had some old PHP code that I have bastardized adapted to try and download the response as a file.
This is my code:
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();
});
I've seen issues about downloading existing files with loopback, but never downloading a REST response as a file.
based on your approach it works like this. In my case 'organisation' is the model.
File: 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.
};
And the remote Method definition (to get the response object)
Organisation.remoteMethod('csvexport',
{
accepts: [
{arg: 'type', type: 'string', required: true },
{arg: 'res', type: 'object', 'http': {source: 'res'}}
],
returns: {},
http: {path: '/csvexport/:type', verb: 'get'}
});
While type is just a get Parameter for different CSV file exports..
Note: I am using "loopback": "^2.10.2",
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With