Ed Angelis Ribeiro
Ed Angelis Ribeiro

Reputation: 109

How to Resize Image before upload to S3 using multer

This is my code, it work fine, I just wish resize the image before up to s3 amazon cloud.

import multer from 'multer';
import path from 'path';
import multerS3 from 'multer-s3';
import aws from 'aws-sdk';

const storageType = {
    s3: multerS3({
        s3: new aws.S3(),
        bucket: 'restsystemplatesimage',
        contentType: multerS3.AUTO_CONTENT_TYPE,
        acl: 'public-read',
        key: (req, file, cb) => {
            console.log(file);
            //const restCod = req.params.data.split('|')
            cb(null, file.originalname);
        }
    })
}

export default {
    storage: storageType['s3'],
    limits: {
        filesize: 1 * 1024 * 1024
    },
    fileFilter: (req, file, cb) => {
        const allowedMimes = [
            "image/jpeg",
            "image/jpg",
            "image/png"
        ];
        if (allowedMimes.includes(file.mimetype)) {
            cb(null, true);
        }else {
            cb( new Error("Invalid file type"));
        }
    }
};

When I print the file on console, it show ...

{
  fieldname: 'image',
  originalname: 'espetinho-de-carne.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg'
}

Shouldn´t the buffer object appear? I can't modify the image if I don't know where it is

please somebody help

Upvotes: 2

Views: 1449

Answers (1)

Ed Angelis Ribeiro
Ed Angelis Ribeiro

Reputation: 109

I found the solution, instead of using the package multer-s3, I used the package multer-sharp-s3, and make these changes to my code

import multer from 'multer';
import path from 'path';
import multerS3 from 'multer-sharp-s3';
import aws from 'aws-sdk';

const storageType = {
    s3: multerS3({
        s3: new aws.S3(),
        Bucket: 'restsystemplatesimage',
        resize: {
            width: 320,
            height: 192
          },
        ACL: 'public-read',
        key: (req, file, cb) => {
            console.log(file);
            //const restCod = req.params.data.split('|')
            cb(null, file.originalname);
        }
    })
}

export default {
    storage: storageType['s3'],
    limits: {
        filesize: 1 * 1024 * 1024
    },
    fileFilter: (req, file, cb) => {
        const allowedMimes = [
            "image/jpeg",
            "image/jpg",
            "image/png"
        ];
        if (allowedMimes.includes(file.mimetype)) {
            cb(null, true);
        }else {
            cb( new Error("Invalid file type"));
        }
    }
};
´´´

Upvotes: 2

Related Questions