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.
getCSV
remote look like? Why not just put this code in that remote method instead of as a hook? – Caprine