Node.js / Express.js- Uploading images to CDN

Node.js / Express.js- Uploading images to CDN

Caveat: Node.js has a maximum heap limit (it's quite low from memory) , streaming into a file and then streaming to cloudinary maybe the best option to you.


To process files from an endpoint in express, I used multer. It accepts multipart/form-data. It has a key value system for text data and it can be configered in different method for files. I was only accepting a single file with it's key being photo.

const upload = multer({ storage: multer.memoryStorage() }).single("photo");

Next we define a promsise for cloudinary.upload_stream, credits to darioblanco for the function below.

function uploadStream(fileBuffer, options) {
  return new Promise((resolve, reject) => {
    cloudinary.uploader
      .upload_stream(options, (error, result) => {
        if (error) {
          reject(error);
        } else {
          resolve(result);
        }
      })
      .end(fileBuffer);
  });
}

Moving on to the part where we upload to cloudinary, note that this is an express.js handler:

const addPhoto = (req, res) => {
  upload(req, res, err => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    if (req.file.buffer === undefined || req.file.buffer === null) {
      res
        .status(402)
        .json({ error: "multipart form with 'photo' as key was not provided" });
      return;
    }
    uploadStream(req.file.buffer, { public_id: `upload_path_to_image` })
      .then(result => {
        return result.secure_url;
      })
      .then(url => {
        res.status(200).json({ url });
      })
      .catch(err => {
        res.status(500).json({ error: err.message });
      });
  });
};