Titsjmen
Titsjmen

Reputation: 809

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());
  }
});

Upvotes: 3

Views: 2763

Answers (1)

MaK
MaK

Reputation: 121

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

Upvotes: 1

Related Questions