0
votes

I need help with uploading two files via multer in my nodejs application. I process them through sharp for resizing, but it cuts both files at once. How can I do to set the settings for each file separately?

Code below:

// main upload function
const upload = multer({

    ...
    sharp: (req, file, cb) => {
        const resizer = Sharp()
            .resize(1024, 1024)
            cb(null, resizer)
    }
})

// for uploading some files
let cpUpload = upload.fields([{ name: 'image1', maxCount: 1 }, { name: 'image2', maxCount: 1 }])

// getting files
router.post('/', cpUpload, async (req, res) => { ... })
2

2 Answers

2
votes

Firstly you have to declare multer function and also you can add any properties to the function. I have mentioned some of the properties as well. here is for more info link

//uploading images and validations
const upload = multer({
    limits: {
        fileSize: 1000000 //maximum size of an image
    },
    fileFilter(req, file, cb) {
        // checking if file extension does not match with jpg,png,jpeg
        if (!file.originalname.match(/\.(jpg|png|jpeg)$/)) {
            return cb(new Error('Please upload a image.')); // if it is then throw an error
        }
        cb(undefined, true);
    }
});

and then you have to declare the route with sharp, basically sharp is

The typical use case for this high-speed Node.js module is to convert large images in common formats to smaller, web-friendly JPEG, PNG and WebP images of varying dimensions.

here is the link for more info.

//create photo
router.post('/',upload.array('pic', 10),async (req, res) => {
        try {
            const promises = req.files.map((file) => {
                return sharp(file.buffer).resize({ width: 1024, 
                                                   height: 1024}).png().toBuffer();
            });

            const buffers = await Promise.all(promises);

            const photos = buffers.map((buffer) => {
                return new Photo({ pic: buffer});
            });

            await Photo.insertMany(photos);

            res.redirect('/');
        } catch (e) {
            res.status(400).redirect('/');
        }
    },
    (error, req, res, next) => {
            res.status(400).redirect('/');
    }
);
0
votes

Sharp method is used to resize all the images we want to upload and its for basic reside to save the storage capacity. There are two methods to achieve what you are looking for. First one if you want to go with you existing one. You can use filter method of the multer and perform what action you want to perform on specific file.

const upload = multer({
    fileFilter: function (req, file, cb) {
        yourFunctionToPerformResize(file, cb);
    }
});

Secondly you can use MulterResizer to resize specific images you want to. Here's the link.

const multer = require('multer');
const MulterResizer = require('multer-resizer');
const resizer = new MulterResizer({
    multer: multer({storage: multer.diskStorage({destination: './'})}),
    tasks: [
        {
            resize: {
                width: 1920,
                height: 1080,
                suffix: 'resized-big'
            }
        },
        {
            resize: {
                width: 100,
                height: 100,
                suffix: 'resized-small'
            }
        },
        {
            cover: {
                width: 160,
                height: 112,
                suffix: 'thumbnail'
            }
        }
    ]
});

router.post('/', auth.ensureAuthentication, resizer.single('file'), function(req, res, next) {
    // All multer-resizer tasks were completed
});