Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image + duplicate(low-res thumbnail) via multerjs

I am building a webapplication that allows users to upload an avatar. However, in addition to the avatar I want to create a thumbnail low-res (e.g. 64 x 64) and store it on my server. Currently I'm using this code to store the image in two directories, but it's the same resolution in both directories. How would I store a different resolution in the thumbnails directory?

 var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads/thumbs');
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname + '-' + Date.now());
  }
});
like image 638
Titsjmen Avatar asked Jan 25 '26 10:01

Titsjmen


1 Answers

You can use sharp for resize you images in your router:

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './uploads')
    },
    filename: (req, file, cb) => {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }
})

and:

router.post('/', upload.single('image'), async (req, res) => {    
    try {
        const { filename: image } = req.file
        await sharp(req.file.path, { failOnError: false })
            .resize(64, 64)
            .withMetadata()
            .toFile(
                path.resolve(req.file.destination, './thumbs', image.replace(/\.(jpeg|png)$/, `.jpg`))
            )
        fs.unlink(req.file.path)
        return res.json({
            thumb_url: '/uploads/thumbs/' + image.replace(/\.(jpeg|png)$/, `.jpg`)
        });
    } catch (err) {
        console.error(err.message);
        res.status(500).send('Server Error!');
    }
});

fs.unlink(req.file.path) remove your orginal image from ./uploads

like image 124
MaK Avatar answered Jan 28 '26 08:01

MaK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!