Search code examples
expressaws-sdkimage-resizingmultermulter-s3

How to resize upload images with express server


I am using multer and multer-s3 to upload an image to s3 bucket.

I want to keep the original image as it is, but need additional thumbnail image. Then upload both of them to s3. I found that image resize can be done using sharp but not sure how to do this particular task.

Can anyone advice how to do this ?

const aws = require('aws-sdk');
const multer = require('multer');
const multerS3 = require('multer-s3');

aws.config.update({
    secretAccessKey: process.env.AWSSecretKey,
    accessKeyId: process.env.AWSAccessKeyId,
});

const s3 = new aws.S3();

const fileFilter = (req, file, cb) => {
    if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
        cb(null, true);
    } else {
        cb(new Error("Invalid file type, only JPEG and PNG is allowed!"), false);
    }
};

const storage = multerS3({
    s3: s3,
    bucket: process.env.S3_Bucket_Name,
    acl: 'public-read',
    metadata: (req, file, cb) => {
        cb(null, {
            fieldName: file.fieldname
        });
    },
    key: (req, file, cb) => {
        cb(null, Date.now().toString())
    }

});

const upload = multer({
    fileFilter: fileFilter,
    storage: storage,
});

module.exports = upload;

Routing is done in following manner

router.post('/post/add', checkAuth, upload.single("photo"), PostController.createPost);

Solution

  • After you saved your image you can resize it easelie.

    You just need to pass the path to the image.

    Note here: You can get the width and height of the image and check if the image needs an resize.

    const sharp = require("sharp");
    
    async function resizeImage(req, res) {
       let { width, height } = await sharp("path/to/image").metadata();
       let resizedImage;
       // you can check here if the image is too big. I will resize it to an width of 400
       if(width > 400) {
          await sharp("path/to/image")
              .resize({ fit: sharp.fit.contain, width: 400 })
              .jpeg({ quality: 90 })
              .toFile("path/to/thumbnail/directory);
       }
    }