【问题标题】:Express - how do I use sharp with multer?Express - 如何在 multer 中使用Sharp?
【发布时间】:2021-01-28 07:32:24
【问题描述】:

我在使用Sharp 方面需要帮助,我希望我的图片在上传时调整大小,但我似乎无法做到这一点。

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

【问题讨论】:

  • this link 包含并实现了用于文件上传的sharp和multer,看看这个

标签: multer sharp


【解决方案1】:

据我所知,您应该将Buffer 传递给锐化而不是路径。 与其调整保存图像的大小,不如在保存之前调整它的大小。要实现这一点,您应该使用multer.memoryStorage() 作为存储。

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

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 2021-01-11
    • 2015-03-03
    • 1970-01-01
    • 2019-05-03
    • 2020-09-03
    • 1970-01-01
    • 2019-10-03
    • 2019-10-22
    相关资源
    最近更新 更多