You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js(Express)图片上传API添加尺寸与格式验证问题

图片上传API的格式与尺寸验证实现

核心思路

要实现这两项验证,最佳时机是在文件写入服务器之前完成,避免无效文件占用存储。我们可以利用multer的fileFilter选项拦截文件,结合image-size模块读取图片尺寸,一次性完成格式和尺寸校验。

步骤1:确认依赖

确保已安装所需包:

npm install multer image-size

步骤2:完整验证代码

const multer = require('multer');
const sizeOf = require('image-size');
const path = require('path');

// 定义允许的图片MIME类型
const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/jpg'];
// 定义允许的尺寸范围(可根据实际需求调整)
const maxAllowedWidth = 1920;
const maxAllowedHeight = 1080;

const storage = multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, './uploads');
  },
  filename: function (req, file, callback) {
    const originalname = file.originalname;
    const fileExt = path.extname(originalname).toLowerCase();
    const exactName = path.basename(originalname, fileExt);
    // 生成唯一文件名避免冲突
    const uniqueFilename = `${exactName}-${Date.now()}${fileExt}`;
    callback(null, uniqueFilename);
  },
});

// 自定义文件过滤器,实现格式与尺寸双重验证
const fileFilter = function (req, file, callback) {
  // 1. 格式验证
  if (!allowedMimeTypes.includes(file.mimetype)) {
    return callback(new Error('仅支持jpg、jpeg、png格式的图片'));
  }

  // 2. 尺寸验证
  sizeOf(file.buffer, function (err, dimensions) {
    if (err) {
      return callback(new Error('无法读取图片尺寸信息'));
    }
    if (dimensions.width > maxAllowedWidth || dimensions.height > maxAllowedHeight) {
      return callback(new Error(`图片尺寸超出限制,最大允许${maxAllowedWidth}x${maxAllowedHeight}`));
    }
    // 验证通过,允许文件上传
    callback(null, true);
  });
};

// 配置multer,应用存储规则和验证过滤器
const upload = multer({ 
  storage: storage,
  fileFilter: fileFilter
}).any('userPhoto');

const uploadavatar = function (req, res) {
  upload(req, res, function(err) {
    if (err) {
      return res.status(400).end(err.message);
    }
    res.end("文件上传成功");
  });
};

module.exports = { uploadavatar };

关键说明

  • 格式验证:通过file.mimetype判断文件类型,比解析扩展名更可靠,能避免扩展名伪造的情况。
  • 尺寸验证:直接读取文件缓冲区file.buffer获取尺寸,无需先将文件写入服务器,既提升效率又避免文件操作错误。
  • 错误反馈:验证不通过时抛出的错误会被传递到upload回调中,直接返回给客户端清晰的错误信息。
  • 文件名处理:使用path模块解析文件名和扩展名,比手动分割字符串更稳定兼容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 05:28:32