Meteor 前端 RESTful API 通过后端 API 下载文件

Meteor 下载文件

问题场景

后端 HTTP server提供一个下载接口,可是须要前端 Meteor 可以给浏览器用户开一个URL来下载这个文件。

举例:在线的Meteor Logo文件就好比后端提供的 RESTful API,然后我们给浏览器客户暴露一个 URL 来下载

Meteor 依赖

安装全部依赖:

meteor add http
meteor add cfs:http-methods
meteor add froatsnook:request

说明:
* cfs:http-methods * 用来给Meteor项目提供一个方便创建 RESTful API 的机会。很方便。


here for details.

* froatsnook:request * 用来给Meteor项目提供一个便利訪问二进制数据的 RESTful API 的机会,也是很简洁方便。支持同步请求。


here for details.

演示样例代码

Meteor server端

if (Meteor.isServer) {

  // exports a RESTful API for browser
  HTTP.methods({

    // name RESTful API as "GET /download-meteor-logo"
    '/download-meteor-logo': function() {

      // A file in streaming, so need to response to browser as a streaming.
      var res = this.createWriteStream();

      // Play as a HTTP client for requesting image.
      // It is Sync way
      var result = request.getSync("https://meteor.com/meteor-logo.png", {
        encoding: null
      });

      var buffer = result.body;
      // TODO: need to set header for response here which transfered by
      // response of logo request.
      res.write(buffer);
      res.end();
    }
  });
} // Meteor.isServer enclosure
  1. 首先得启动 Meteor 服务
meteor --port 3000
  1. 打开浏览器訪问 http://localhost:3000/download-meteor-logo

效果示意图

原文地址:https://www.cnblogs.com/mfmdaoyou/p/7109729.html