4
votes

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 :)

2
did you find a solution ? if so answer your own question. thanksChiKa LiO
I have your EXACT same problem. PLEASE if you've found a solution post it down here!Mattia Rasulo

2 Answers

2
votes

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.

1
votes

Edit (12/24/2020): I can no longer recommend this package and I'm no longer using it in my projects. This package lacks many of the other features multerS3 has, including AUTO_CONTENT_TYPE which I use often to automatically set the content-type in S3. I highly recommend just sticking to multerS3 or not even using multerS3 at all and handling the multipart form data yourself with something like multiparty.

Original post: I found this package on npm called multer-sharp-s3 Link: https://www.npmjs.com/package/multer-sharp-s3.

I'm using this implementation:

var upload = multer({
    storage: multerS3({
        s3: s3,
        ACL: 'public-read',
        Bucket: s3Bucket,
        Key: (req, file, cb) => {
            cb(null, file.originalname);
        },
        resize: {
            width: 100,
            height: 100
        }
    }),
    fileFilter: fileFilter
});

Hope this helps!