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

如何实现点击按钮时验证上传图片的分辨率?

实现图片上传前的分辨率验证

HTML 结构示例

先搭建对应的DOM元素,包含文件选择框、验证触发按钮和上传按钮:

<input type="file" id="imageFile" accept="image/*">
<button id="verifyBtn">选择推荐分辨率文件</button>
<button id="uploadBtn" disabled>更新至服务器</button>
<p id="errorMsg" style="color: red;"></p>

JavaScript 验证逻辑

下面是核心的验证函数,你可以根据需求修改requiredWidth和requiredHeight的值来匹配推荐分辨率:

// 定义推荐的分辨率
const requiredWidth = 1920;
const requiredHeight = 1080;

// 获取DOM元素
const imageFileInput = document.getElementById('imageFile');
const verifyBtn = document.getElementById('verifyBtn');
const uploadBtn = document.getElementById('uploadBtn');
const errorMsg = document.getElementById('errorMsg');

// 验证分辨率的函数
function validateImageResolution(file) {
  return new Promise((resolve, reject) => {
    if (!file || !file.type.startsWith('image/')) {
      reject('请选择有效的图片文件');
      return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
      const img = new Image();
      img.onload = function() {
        if (img.width === requiredWidth && img.height === requiredHeight) {
          resolve({ width: img.width, height: img.height });
        } else {
          reject(`图片分辨率不符合要求,需要 ${requiredWidth}x${requiredHeight},当前为 ${img.width}x${img.height}`);
        }
      };
      img.onerror = function() {
        reject('无法加载图片,请检查文件是否损坏');
      };
      img.src = e.target.result;
    };
    reader.readAsDataURL(file);
  });
}

// 绑定验证按钮点击事件
verifyBtn.addEventListener('click', async () => {
  const file = imageFileInput.files[0];
  if (!file) {
    errorMsg.textContent = '请先选择图片文件';
    uploadBtn.disabled = true;
    return;
  }

  try {
    await validateImageResolution(file);
    errorMsg.textContent = '';
    uploadBtn.disabled = false;
    alert('图片分辨率符合要求,可以上传');
  } catch (err) {
    errorMsg.textContent = err;
    uploadBtn.disabled = true;
  }
});

// 上传按钮点击事件(替换成你实际的上传逻辑)
uploadBtn.addEventListener('click', () => {
  const file = imageFileInput.files[0];
  // 构建FormData用于上传
  const formData = new FormData();
  formData.append('image', file);
  
  // 示例:用fetch发送上传请求
  fetch('/your-upload-endpoint', {
    method: 'POST',
    body: formData
  })
  .then(response => response.json())
  .then(data => {
    console.log('上传成功', data);
    alert('文件已更新至服务器');
  })
  .catch(err => {
    console.error('上传失败', err);
    alert('上传失败,请重试');
  });
});

关键说明

  • 文件类型校验:通过file.type.startsWith('image/')确保用户选择的是图片文件
  • 分辨率验证:利用FileReader读取图片为DataURL,再通过Image对象加载后获取真实宽高,和推荐分辨率对比
  • 状态控制:验证通过后才启用上传按钮,避免无效的服务器请求
  • 错误提示:针对未选文件、非图片、分辨率不符、图片损坏等场景给出明确提示

你可以根据实际需求调整:

  • 修改requiredWidth和requiredHeight为你的推荐分辨率
  • 调整错误提示的样式或显示方式
  • 替换上传按钮里的服务器请求逻辑为项目实际接口

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 21:32:57