如何将包含图像文件的流发送到环回中的远程方法?

How can I send a stream containing an image file to a remote method in loopback?

我目前正在尝试使用环回生成 API,它允许我发送手写字符的 28x28 图像文件,并让图像由张量流网络处理,return 预测网络认为角色是什么。

然而,为了做到这一点,我需要能够发送要处理的图像,而不必先将文件保存在服务器上,但我找不到如何做这样的事情。诸如 loopback-component-storage 之类的模块很棒,但我不想使用一个路由发送图像,另一个路由处理该图像,然后第三个路由删除包含该图像文件的容器,使过程需要三个不同的请求。

因此归根结底,有什么方法可以将图像附加到请求中,这样流就可以被 API 读取和解释,而无需先保存文件的副本服务器上的其他地方?

提前致谢

我推荐以下解决方案:

首先,将您的服务器中间件配置为解析图像请求主体:

  1. 安装body-parser依赖。

    $ npm install --save body-parser
    
  2. 通过将以下内容添加到 server/middleware.json 文件的 parse 部分来配置 raw 解析器:

    {
      "body-parser#raw": {
        "limit": "100kb",
        "type": "image/*"
      }
    }
    

    "limit" 选项设置允许的最大请求正文大小。您不想允许任意大小以防止恶意客户端在 "out of memory" 错误时使您的服务器崩溃。

    "type" 选项配置应由该中间件解析的内容类型。在我上面的示例中,我允许所有图像类型。

接下来,实现一个接受请求正文的远程方法。感谢原始正文解析器,正文流将已经为您转换为 Buffer。在我下面的例子中,我有一个简单的方法来响应 base64 编码的正文。

module.exports = function(Image) {
  Image.analyze = async function(data) {
    // Reject non-image requests, e.g. JSON
    if (!Buffer.isBuffer(data)) {
      const err = new Error('Unsupported media type'); 
      err.statusCode = 415;
      throw err;
    }

    // data is a Buffer containing the request body
    return data.toString('base64');
  };

  Image.remoteMethod('analyze', {
    accepts: [
      // {source: 'body'} is the important part
      {arg: 'data', type: 'object', http: {source: 'body'}},
    ],
    returns: {root: true, type: 'string'},
    http: {path: '/analyze', verb: 'post'},
  });
};