用node.js上传图像并表达的简单方法?

问题描述:

我发现很少有文章解释该过程,但是其中大多数都不是最新的. 您如何在node.js中处理图片上传?

I've found few articles explaining the process but most of them are not up do date. How do you handle image upload in node.js?

我使用 busboy中间件快速解析多部分/表单数据请求中的图像,效果很好.

I use busboy middleware in express to parse out images in a multipart/form-data request and it works pretty nice.

我的代码如下:

const busboy = require('connect-busboy');
//...
app.use(busboy());

app.use(function parseUploadMW(req,res,next){
  req.busboy.on('file', function onFile(fieldname, file, filename, encoding, mimetype) {
    file.fileRead = [];
    file.on('data', function onData(chunk) {
      this.fileRead.push(chunk);
    });
    file.on('error', function onError(err) {
      console.log('Error while buffering the stream: ', err);
      //handle error
    });
    file.on('end', function onEnd() {
      var finalBuffer = Buffer.concat(this.fileRead);
      req.files = req.files||{}
      req.files[fieldname] = {
        buffer: finalBuffer,
        size: finalBuffer.length,
        filename: filename,
        mimetype: mimetype.toLowerCase()
      };
    });
  });
  req.busboy.on('finish', function onFinish() {
    next()
  });
  req.pipe(req.busboy);
})

然后,文件将在快速路线的req.files中位于您的req对象中.

Then files will be in the req object for you at req.files in your express routes.

此技术适用于小图像.如果您要进行一些硬核上载,则可能要考虑将文件流化(以节省内存)到其目的地-如s3或类似文件-

This technique works fine for small images. If you are doing some hardcore uploading, you may want to consider streaming the files (to save memory) to their destination - like s3 or similar - which can also be achieved with busboy

另一个受欢迎且不错的软件包是: https://github.com/andrewrk/node-多方.

Another package that is popular and also decent is: https://github.com/andrewrk/node-multiparty.