我怎样才能用 multer 和 sharp 改变图像的大小?

How can i change the size of images with multer with sharp?

我构建了一个网络应用程序,并希望将我的图像调整得更小,以提高我个人资料图片的质量。我正在使用“multer”上传图片,使用 sharp package 调整大小。

出于某种原因我得到这个错误:

"[0] [Error: D:\DevConnectors\public\resizedf4f4e0bb295ba36042536bf.jpg: unable to open for write
[0] windows error: The storage control block address is invalid."

我的代码:

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, DIR)
  },
  filename: (req, file, cb) => {
    var typeFile = file.originalname.split(".").pop()
    const fileName = req.user.id + "." + typeFile
    cb(null, fileName)
  },
})

var upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    if (
      file.mimetype == "image/png" ||
      file.mimetype == "image/jpg" ||
      file.mimetype == "image/jpeg"
    ) {
      cb(null, true)
    } else {
      return cb(new Error("Only .png, .jpg and .jpeg format allowed!"), false)
    }
  },
})

const Profile = require("../../moduls/Profile")
const User = require("../../moduls/User")

//@route GET/api/profile/me
//@desc Get current users profile
//@access Private

router.post(
  "/upload",
  [auth, upload.single("imageProfile")],
  async (req, res) => {
    try {
      console.log(req.file)
      const { filename: image } = req.file
      await sharp(req.file.path)
        .resize(150)
        .jpeg({ quality: 50 })
        .toFile(path.resolve(req.file.destination, "resized", image))

      fs.unlinkSync(req.file.path)

      const url = req.protocol + "://" + req.get("host")
      let user = await User.findById(req.user.id)
      const profile = await Profile.findOne({ user: req.user.id })
      //Update
      if (user) {
        user.avatar = url + "/public/" + req.file.filename
        await user.save()
        return res.json(profile)
      }
    } catch (err) {
      console.log(err)
    }
  }
)

这发生在这一行:

path.resolve(req.file.destination,'resized',image))

我做错了什么?我正在使用 sharp 文档。

试试这个 multer的配置(根据需要改)

import multer from "multer";
import sharpe from "sharp";

const upload = multer({      //multer configuration
  //dest: "avatars",       //so that buffer is available in route handler
  limits: {
    fileSize: 1000000,
  },
  fileFilter(req, file, cb) {        // object method shorthand syntax
    if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) { //.match for using regex b/w (//)
      return cb(new Error("Please upload a IMAGE"));
    }
    cb(undefined, true);
  },
});

像这样在你的路线手柄中处理锋利。

router.post(
           "path",
          upload.single("avatar"),
       async (req, res) => {      
       const buffer = await sharpe(req.file.buffer)
            .png()
            .resize({
              width: 300,
              height: 300
            })
            .toBuffer();
          req.user.avatar = buffer;
          await req.user.save();
          res.send();
        },
        (error, req, res, next) => {
          //to tell express this how mutler/s error should be handled
          res.status(400).send({
            error: error.message,
          });
        }
    );

我遇到了同样的问题,在我的情况下,问题是目录(在您的情况下为“已调整大小”)尚不存在。因此,要么手动创建它,要么像这样以编程方式创建它:

const targetPath = path.resolve(req.file.destination, 'resized')
if (!existsSync(targetPath)) {
  mkdirSync(targetPath);
}
await sharp(...)