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

如何通过JS/jQuery设置<input type='image'>上传文件的限制规则

实现方案

可以通过JS/jQuery实现所有你提到的上传限制,注意前端仅作为体验优化手段,必须配套后端校验避免规则被绕过。

补充说明:你提到的<input type="image">实际是图像形式的提交按钮,若要实现图片文件选择功能,推荐使用<input type="file" accept="image/*">,以下示例基于该组件实现,逻辑可完全复用至你的场景。

校验规则对应实现方式

你需要的4项限制对应的实现逻辑如下:

  • 文件大小限制:直接读取文件对象的size属性计算,36MB对应字节数为 36 * 1024 * 1024 = 37748736 B
  • 宽高比1:1:校验图片原始宽度等于原始高度即可
  • 最小尺寸3000×3000px:校验宽高均≥3000
  • 最大尺寸5000×5000px:校验宽高均≤5000

完整代码示例

// 给文件选择框绑定change事件,替换选择器为你页面实际的元素ID/类名
$('#image-upload-input').on('change', function(e) {
  const file = e.target.files[0];
  if (!file) return;

  // 第一步:校验文件大小
  const maxAllowedSize = 36 * 1024 * 1024;
  if (file.size > maxAllowedSize) {
    alert('文件大小不能超过36MB');
    $(this).val(''); // 清空错误选择
    return;
  }

  // 第二步:加载图片校验尺寸和宽高比
  const validateImg = new Image();
  validateImg.src = window.URL.createObjectURL(file);
  validateImg.onload = function() {
    const originWidth = this.naturalWidth;
    const originHeight = this.naturalHeight;

    // 校验宽高比1:1
    if (originWidth !== originHeight) {
      alert('图片宽高比必须为1:1');
      $('#image-upload-input').val('');
      window.URL.revokeObjectURL(this.src);
      return;
    }

    // 校验尺寸范围
    if (originWidth < 3000 || originHeight < 3000) {
      alert('图片最小尺寸为3000×3000px');
      $('#image-upload-input').val('');
      window.URL.revokeObjectURL(this.src);
      return;
    }
    if (originWidth > 5000 || originHeight > 5000) {
      alert('图片最大尺寸为5000×5000px');
      $('#image-upload-input').val('');
      window.URL.revokeObjectURL(this.src);
      return;
    }

    // 所有校验通过,执行后续上传逻辑
    alert('图片符合要求,可以上传');
    window.URL.revokeObjectURL(this.src);
  }
  // 非图片文件异常处理
  validateImg.onerror = function() {
    alert('请选择有效的图片文件');
    $('#image-upload-input').val('');
  }
})

WordPress后端补充说明

前端校验可被人为绕过,你需要在WordPress侧通过wp_handle_upload_prefilter钩子添加相同的校验规则,避免不符合要求的文件被上传到服务器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:06:06