1

I am trying to resize an image prior to uploading it to Amazon S3. I have found documentation on how to achieve this, but I suspect that my implementation is incorrect. I am including the code below. What am I doing wrong?

const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  } else {
    cb(new AppError('Not an image! Please upload images only.', 400), false);
  }
};

const upload = multer({
  storage: multerS3({
    s3: s3,
    acl: 'public-read',
    bucket: 'BUCKETNAME',
    contentType: multerS3.AUTO_CONTENT_TYPE,
  }),
  fileFilter: multerFilter,
  shouldTransform: function (req, file, cb) {
    cb(null, /^image/i.test(file.mimetype));
  },
  transforms: [
    {
      id: 'original',
      key: function (req, file, cb) {
        cb(null, 'image-original.jpg');
      },
      transform: function (req, file, cb) {
        cb(null, sharp().resize(100, 100).jpg());
      },
    },
  ],
});
Chris Clark
  • 488
  • 2
  • 19

1 Answers1

1

I was able to figure this out. The code below worked, using multer-s3-image-transform from npm.

const upload = multer({
  storage: multerS3({
    s3: s3,
    acl: 'public-read',
    bucket: 'BUCKETNAME',
    contentType: multerS3.AUTO_CONTENT_TYPE,
    transforms: () =>
      sharp().resize(250, 250).jpeg({
        progressive: true,
        quality: 80,
      }),
  }),
  fileFilter: multerFilter,
});
Chris Clark
  • 488
  • 2
  • 19