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

I built a web app and want to resize my images to be smaller for better quality to my profile pictures. I am using "multer" for upload picture and sharp package for resizing.

For some reason i get this error:

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

My code:

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

This happens at this line :

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

What am i doing wrong? i am using sharp docs.



Solution 1:[1]

I had the same problem, and in my case the issue was that the directory (in your case "resized") didn't exist yet. So either create it manually or programmatically like this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Justin H.