Search code examples
node.jsamazon-s3sharpmulter-s3

Multer-S3 with sharp upload and resize


I've been able to upload to s3 an image file using multer-s3 library but now I'm trying to add the sharp library to resize and rotate but can't figure out where or how it needs to go. This is my current code that works for uploading:

var options = {
'endpoint' : 'https://xxx',
'accessKeyId' : '123',
'secretAccessKey' : '123abc',
'region' : 'xxx'
};

 const s3 = new aws.S3(options);

const upload = multer({
storage: multerS3({
    s3: s3,
    bucket: 'wave',
    acl: 'public-read',
    metadata: function (req, file, cb) {
      cb(null, Object.assign({}, req.body));
    },
    key: function (request, file, cb) {
        console.log('inside multerS3',file);
        cb(null, file.originalname);
    }
})
}).array('file', 1);

app.post('/upload/', (req,res) => {
   upload(req,res, async function (error) {
     if(error){
        res.send({ status : error });
     }else{
        console.log(req.files[0]);
        res.send({ status : 'true' });
     }
    });
 });

And do something like this with the file:

 sharp(input)
 .resize({ width: 100 })
 .toBuffer()
 .then(data => {
   // 100 pixels wide, auto-scaled height
 });

Any help would be greatly appreciated :)


Solution

  • Ok so I never found an actual solution to this but I did get a recommendation which is the route I went with. Because of performance considering multiple uploads by multiple users to do a resize, rotate and whatever else to the image at time of upload is not the best solution because that would be heaving on the server. The way we went with was have a cdn server and on that server have a script that detects when a new file is uploaded with goes ahead and does resizing and rotating.

    I know it's not an actual fix to the original problem but it was the best solution I got considering performance and optimization.