【问题标题】:How can i change the size of images with multer with sharp?如何使用具有锐利的 multer 更改图像的大小?
【发布时间】:2020-12-21 08:37:55
【问题描述】:

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

由于某种原因,我收到此错误:

"[0] [Error: D:\DevConnectors\public\resized\5f4f4e0bb295ba36042536bf.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))

我做错了什么?我正在使用清晰的文档。

【问题讨论】:

    标签: node.js multer


    【解决方案1】:

    试试这个 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,
              });
            }
        );
    

    【讨论】:

    • 存储呢?在我的 multer 中,我将文件保存在公共目录中,如何配置我的文件以保存在公共目录中?
    • 只需将要存储文件的目录的“dest”属性和路径添加到 multer configuration 中。 const upload = multer({ dest: 'path/to/directory' })。如果这个答案无论如何帮助你接受它,以便将来可以帮助其他人:)
    • @JatinMehrotra 嗨,你能看看这个问题吗?stackoverflow.com/questions/65465145/…
    • @JatinMehrotra req.file.buffer 未定义(根本没有缓冲区)并且 req.file.path 说(输入文件丢失)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-07
      • 2021-04-20
      • 1970-01-01
      • 2021-11-13
      • 2018-05-07
      • 2014-10-31
      • 2021-12-16
      • 2018-09-11
      • 1970-01-01
      相关资源
      最近更新 更多