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

3

我目前正在尝试使用Loopback创建一个API,使我能够发送一张28x28的手写字符图像文件,并通过tensorflow网络处理该图像,并返回网络认为该字符是什么的预测结果。

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

因此,问题变成了这样,是否有任何方法可以将图像附加到请求中,以便流可以被读取和解释,而无需首先将文件的副本保存到其他地方的服务器上?

提前感谢您的帮助。


当你谈论上传文件时,你是指将其上传为像从HTML表单(input type=file)发送的方式吗?也就是说,作为可能的多个multipart条目之一,还是可以直接在请求体中以图像有效负载的形式发送到服务器作为唯一发送的数据? - Miroslav Bajtoš
我想直接在请求体中发送图像文件,这样我就可以将其传递给Image类的实例,在其中将图像的源设置为请求中包含的文件。 - Glenn Keates
1个回答

5
我推荐以下解决方案:
首先,配置您的服务器中间件以解析图像请求正文:
  1. Install body-parser dependency.

    $ npm install --save body-parser
    
  2. Configure the raw parser by adding the following content to parse section of your server/middleware.json file:

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

    The "limit" option sets the maximum allowed request body size. You don't want to allow arbitrary size to prevent malicious clients from crashing your server on "out of memory" error.

    The "type" option configures content-types that should be parsed by this middleware. In my example above, I am allowing all image types.

接下来,实现一个接收请求主体的远程方法。由于使用了原始主体解析程序,主体流已经被转换为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'},
  });
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接