Express - how do I use sharp with multer?

6k views Asked by At

I need help with using sharp, I want my images to resize when uploaded but I can't seem to get this right.

router.post("/", upload.single("image"), async (req, res) => {
    const { filename: image } = req.file;

    await sharp(req.file.path)
        .resize(300, 200)
        .jpeg({ quality: 50 })
        .toFile(path.resolve(req.file.destination, "resized", image));

    fs.unlinkSync(req.file.path);
    res.send("sent");
});
1

There are 1 answers

0
Miad Abdi On

As I know you should pass a Buffer to sharp not the path. Instead of resizing saved image, resize it before save. to implement this, you should use multer.memoryStorage() as storage.

const multer = require('multer');
const sharp = require('sharp');

const storage = multer.memoryStorage();

const filter = (req, file, cb) => {
    if (file.mimetype.split("/")[0] === 'image') {
        cb(null, true);
    } else {
        cb(new Error("Only images are allowed!"));
    }
};

exports.imageUploader = multer({
    storage,
    fileFilter: filter
});

app.post('/', imageUploader.single('photo'), async (req, res, next) => {
    // req.file includes the buffer
    // path: where to store resized photo
    const path = `./public/img/${req.file.filename}`;

    // toFile() method stores the image on disk
    await sharp(req.file.buffer).resize(300, 300).toFile(path);
    next();
});