You need to enable JavaScript to run this app. 使用multer上传图片搭配sharp实现头像缩放时文件写入报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用multer上传图片搭配sharp实现头像缩放时文件写入报错如何解决

multer+sharp实现图片压缩上传时的写入报错问题

问题描述

开发Web应用时,为实现个人头像的尺寸压缩、展示加载优化需求,使用multer接收用户上传的图片、使用sharp完成图片缩放处理,运行时触发Windows系统层的文件写入错误。

报错信息

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

错误触发位置为path.resolve(req.file.destination,'resized',image)参与的sharp文件写入逻辑,代码编写参考了sharp官方文档示例。

现有实现代码

multer上传配置

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 POST /api/profile/upload
//@desc 上传并处理用户头像
//@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)
    }
  }
)

问题根因

  • 核心触发原因:代码尝试写入文件的目标路径public/resized目录未提前创建。Windows系统下,若文件写入路径的父级目录不存在,sharp尝试获取文件写入句柄时会触发系统层“存储控制块地址无效”的报错,而非返回常见的“目录不存在”提示。
  • 附带逻辑缺陷:代码压缩后的图片实际存储在public/resized/目录下,但给用户记录的头像路径直接拼接了/public/+原文件名,和实际文件存储位置不匹配,即使解决写入报错,也会出现头像资源404的问题;同时临时存储的原始上传图片删除逻辑虽然存在,但未考虑文件写入失败时的异常清理场景。

修复方案

  • 首先在sharp执行文件写入前,递归创建目标压缩图片的存储目录,使用Node.js内置fs模块的递归创建能力,避免目录不存在导致的写入错误,示例代码:
// 前置依赖引入:fs、path模块
// 拼接压缩目录的完整路径
const resizedDir = path.join(req.file.destination, "resized")
// 递归创建目录,目录已存在时不会抛出重复创建错误
fs.mkdirSync(resizedDir, { recursive: true })

// 拼接最终压缩文件的完整写入路径
const resizedFilePath = path.join(resizedDir, image)
// 替换原有的写入逻辑
await sharp(req.file.path)
  .resize(150)
  .jpeg({ quality: 50 })
  .toFile(resizedFilePath)
  • 修正头像路径的拼接逻辑,匹配压缩后文件的实际存储位置,确保前端可以正常访问到压缩后的头像资源。

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.29 02:45:04