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

NextJS中头像上传前检查图片尺寸是否小于512x512的方案

最简实现:上传头像前检查图片尺寸(≤512x512)

直接用浏览器原生API就能实现,不需要依赖Next.js的Image组件,完全在客户端完成尺寸校验,代码如下:

'use client';

import { useState } from 'react';

export default function AvatarUpload() {
  const [errorMsg, setErrorMsg] = useState('');

  const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFile = e.target.files?.[0];
    if (!selectedFile) return;

    // 可选:先校验文件类型
    if (!selectedFile.type.startsWith('image/')) {
      setErrorMsg('请选择图片格式的文件');
      return;
    }

    const fileReader = new FileReader();
    fileReader.onload = (loadEvent) => {
      const img = new Image();
      img.onload = () => {
        // 检查尺寸是否符合要求
        if (img.width > 512 || img.height > 512) {
          setErrorMsg('图片尺寸不能超过512x512');
          return;
        }
        // 尺寸合规,执行上传逻辑
        setErrorMsg('');
        uploadAvatarToServer(selectedFile);
      };
      img.src = loadEvent.target?.result as string;
    };
    fileReader.readAsDataURL(selectedFile);
  };

  const uploadAvatarToServer = (file: File) => {
    // 这里替换成你的上传逻辑
    const formData = new FormData();
    formData.append('avatar', file);
    fetch('/api/upload-avatar', {
      method: 'POST',
      body: formData,
    })
      .then(res => res.json())
      .then(data => console.log('上传成功', data))
      .catch(err => console.error('上传失败', err));
  };

  return (
    <div>
      <input type="file" accept="image/*" onChange={handleFileSelect} />
      {errorMsg && <p style={{ color: '#dc2626' }}>{errorMsg}</p>}
    </div>
  );
}

说明

  • 代码是Next.js客户端组件(通过'use client'声明),所有校验逻辑在浏览器端完成,无需服务端介入
  • 用原生Image对象做尺寸检查,轻量无冗余,比Next.js的Image组件更适合单纯的校验场景
  • 可根据需求额外添加文件大小限制、格式细化校验等逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 22:14:52