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

如何为jQuery图片上传添加指定尺寸校验并移除无效预览?

为SpartanMultiImagePicker添加图片尺寸校验功能

你可以通过修改onAddRow回调函数,实现图片尺寸的校验逻辑,当上传图片的宽(1000px)高(1250px)不匹配时,自动移除预览并提示错误。以下是修改后的完整代码:

$("#thumbnail").spartanMultiImagePicker({
    fieldName: 'image',
    maxCount: 1,
    rowHeight: 'auto',
    groupClassName: 'col-12',
    maxFileSize: '',
    placeholderImage: {
        image: '{{ asset('assets/back-end/img/400x400/img2.jpg') }}',
        width: '100%',
    },
    dropFileLabel: "Drop Here",
    onAddRow: function(index, file) {
        // 创建图片对象读取真实尺寸
        const img = new Image();
        const reader = new FileReader();
        
        reader.onload = function(e) {
            img.src = e.target.result;
            
            img.onload = function() {
                // 校验尺寸是否符合1000×1250要求
                if (this.width !== 1000 || this.height !== 1250) {
                    // 移除当前无效图片的预览行
                    $("#thumbnail").spartanMultiImagePicker('removeRow', index);
                    // 弹出尺寸错误提示
                    toastr.error(
                        '{{ \App\CPU\translate('Image size must be 1000px(width) × 1250px(height)') }}', 
                        {
                            CloseButton: true,
                            ProgressBar: true
                        }
                    );
                }
            };
        };
        
        reader.readAsDataURL(file);
    },
    onRenderedPreview: function(index) {

    },
    onRemoveRow: function(index) {

    },
    onExtensionErr: function(index, file) {
        toastr.error(
            '{{ \App\CPU\translate('Please only input png or jpg type file') }}', 
            {
                CloseButton: true,
                ProgressBar: true
            }
        );
    },
    onSizeErr: function(index, file) {
        toastr.error('{{ \App\CPU\translate('File size too big') }}', {
            CloseButton: true,
            ProgressBar: true
        });
    }
});

关键逻辑说明

  • 读取真实尺寸:借助FileReader把上传文件转为DataURL,赋值给Image对象,在图片加载完成后获取原始宽高
  • 尺寸校验判断:严格匹配1000px宽、1250px高的要求,不满足则触发后续处理
  • 移除无效预览:调用插件内置的removeRow方法,传入当前图片索引,直接删除对应的预览行
  • 统一提示风格:沿用项目已有的toastr组件展示错误信息,保持交互体验一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 23:46:02