nodejs 微信下载的图片转Base64
发布于 9 年前 作者 xsmallbird 5970 次浏览 最后一次编辑是 8 年前 来自 问答
controller.action('image', function * (next) {
  var mediaId, token, response, url;

  var base64, type, prefix;

  this.checkQuery('mediaId').notEmpty();  // 参数验证
  if (this.errors) {
    this.body = kit.wrapResponse(true, kit.popValue(this.errors[0]));
    return;
  };
  
  token = yield base.getAccessToken(); // 获取access_token
  url = resource.genFetchImage(token, mediaId); // 请求图片的链接
  response = yield request.get(url); // 通过co-request向微信服务器发出请求
  
  // 处理响应,组合base64图片
  type = response.headers["content-type"];
  prefix = "data:" + type + ";base64,";
  base64 = new Buffer(response.body, 'binary').toString('base64');
  
  this.body = prefix + base64;
  yield next;
});

以上代码是我写的控制器,功能是:从微信服务器下载图片,并将其转换成base64格式的。代码是成功执行了,可返回的结果在浏览器img标签里显示不出来。

运行环境

  • node v0.12.2
  • koa v0.20.0
  • controller是我自己写的类

调试+Google+Baidu一晚,还是没能解决。不过调用 fs.writeFile(filename, data[, options], callback) 接口能够下载图片下来。

小白一枚,各路大侠尽情喷我!

3 回复

返回给页面的时候,append进去

yield 关键字怎么用?? 要引用包吗,还是升级node.js

@mrlong 这是es6的特性

回到顶部