如何在不进行磁盘写入的情况下处理Express.js中的POST文件 [英] How to handle POSTed files in Express.js without doing a disk write

查看:91
本文介绍了如何在不进行磁盘写入的情况下处理Express.js中的POST文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to allow users to use a form to upload (POST) an image file to my Express.js web application. Upon receipt, my web application will POST it to the GetChute API (an image web service).

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

I don't want my server temporarily writing the image to disk - instead it should store the image to a variable, and send it to GetChute.

默认情况下,我认为2个Express中间件项(Connect和Formidable)提供了一种从POST自动执行磁盘写入的好方法,但是我该如何规避它们直接访问字节流,从而避免磁盘写入?

By default, 2 Express middleware items (Connect and Formidable) I think are providing a nice way of automatically doing disk writes from POSTs, but how would I circumvent them to directly access the bytestream so I can avoid a disk write?

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

I suspect that someone smarter than me can come up with a tidier solution than was arrived at for a similar question recently:

通过Express上传的流文件.js到gm消除重复写入

谢谢!

推荐答案

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

Can you directly stream the request to 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

Of course, you can adjust the request to GetChute. Be careful, you might have to decode the multipart/form-data.

这篇关于如何在不进行磁盘写入的情况下处理Express.js中的POST文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆