Artur Stary Artur Stary - 17 days ago 13
Node.js Question

Simple way to upload image with node.js and express?

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?

Answer

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

My code looks something like:

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);
})

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

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

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