简体   繁体   English

使用Restangular请求从REST API下载文件

[英]Download a file from REST API with Restangular request

I've got a simple node.js + Restify backend with standard CORS settings and this endpoint: 我有一个简单的node.js + Restify后端,标准的CORS设置和这个端点:

 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. 它想要做的是创建CSV文件并将其返回。

It works great when I simply type in the endpoint address to web browser and hit enter. 当我只是在网络浏览器中键入端点地址并按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:

 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? 有没有办法使用Restangular? Or maybe I need to use something else for this? 或者我可能需要为此使用别的东西?

I am not sure if Restangular can do that, but I am using FileSaver script for stuff like that. 我不确定Restangular是否可以做到这一点,但我正在使用FileSaver脚本来做这样的事情。 Add Filesaver to your HTML head and then: 将Filesaver添加到HTML头,然后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM