Download a file from REST API with Restangular request

别来无恙 提交于 2019-12-11 03:32:15

问题


I've got a simple node.js + Restify backend with standard CORS settings and this endpoint:

var file = '1,5,8,11,12,13,176,567,9483';

server.get('/download', function(req, res, next) {
  res.set({"Content-Disposition": "attachment; filename='numbers.csv'"});
  res.setHeader("Content-type", "text/csv");
  res.send(file);
  return next();
}, function(err) {
  res.send(err);
});

What it's suppose to do is to is to create CSV file and return it.

It works great when I simply type in the endpoint address to web browser and hit enter. The file gets downloaded properly.

But when I try to do the same thing, but instead of using browser's address bar I use Restangular like that:

Restangular.one('download').get().then(function (res) {
    console.log(res);
});

it just writes response to console, but no file is being downloaded.

Is there a way to do this using Restangular? Or maybe I need to use something else for this?


回答1:


I am not sure if Restangular can do that, but I am using FileSaver script for stuff like that. Add Filesaver to your HTML head and then:

Restangular.one('download').get().then(function (res) {
    var file = new Blob([res], { type: 'text/csv' });
    saveAs(file, 'something.csv');
});


来源:https://stackoverflow.com/questions/31820506/download-a-file-from-rest-api-with-restangular-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!