如何在不执行磁盘写入的情况下处理Express.js中的POSTed文件

时间:2012-08-06 17:16:02

标签: node.js post express

我想允许用户使用表单将图像文件上传(POST)到我的Express.js Web应用程序。收到后,我的Web应用程序会将其发布到GetChute API(图像Web服务)。

我不希望我的服务器暂时将图像写入磁盘 - 而是应该将图像存储到变量中,然后将其发送到GetChute。

默认情况下,2个Express中间件项目(Connect和Formidable)我认为提供了一种从POST自动执行磁盘写入的好方法,但是如何绕过它来直接访问字节流以便我可以避免磁盘写入? / p>

我怀疑比我更聪明的人可以提出比最近针对类似问题得出更整洁的解决方案:

Stream file uploaded with Express.js through gm to eliminate double write

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以直接将请求流式传输到GetChute吗?

app.post('/upload', function(req, res) {
  var chuteReq = http.request({
    host: 'api.getchute.com',
    path: '/x/y/z',
    method: 'POST'
  }, function(chuteRes) {
    var chuteBody = '';

    chuteRes.on('data', function(chunk) {
      chuteBody += chunk;
    });

    chuteRes.on('end', function() {
      var chuteJSON = JSON.parse(chuteBody);

      // check the result and build an appropriate response.
      res.end(chuteJSON);
    });
  });

  // pipe the image data directly to GetChute
  req.pipe(chuteReq);      
});

当然,您可以调整对GetChute的请求。请注意,您可能需要解码multipart/form-data