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

本文介绍了如何在Meteor前端应用中通过后端API实现文件下载。首先阐述了问题场景,即后端提供下载接口,前端需提供URL供用户下载。接着提到了Meteor项目的两个关键依赖:cfs:http-methods和froatsnook:request,它们用于构建RESTful API和进行二进制数据请求。最后,给出了Meteor服务器端的示例代码,以及如何在浏览器中查看和下载Meteor Logo的步骤。
摘要由CSDN通过智能技术生成

Meteor 下载文件

问题场景

后端 HTTP 服务器提供一个下载接口,但是需要前端 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 服务器端

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

效果示意图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值