GeneXus 18u11+WorkWithPlus:验证图片尺寸为300x300dip的方案
GeneXus 18 Update 11 + WorkWithPlus:300x300dip图片上传限制方案
一、WorkWithPlus内置能力结合实现
WorkWithPlus本身没有直接的“精确尺寸匹配”开关,但可以通过客户端验证配置+自定义脚本快速实现需求,步骤如下:
启用客户端验证
- 打开你的WorkWithPlus对象,找到目标Image类型字段
- 在右侧属性面板切换到
Validation标签,勾选Client Validation——这会让校验在用户选完文件后立刻触发,不用等提交到服务端
添加自定义尺寸校验脚本
- 在字段的
Client Validation Script属性中粘贴以下代码,记得把{FieldId}换成该字段实际的HTML ID(可在GeneXus的Field.Id属性中查看):// 绑定文件选择事件 document.getElementById('{FieldId}').addEventListener('change', function() { const input = this; if (!input.files || !input.files[0]) return; const reader = new FileReader(); reader.onload = function(e) { const img = new Image(); img.onload = function() { // 注:若页面未设置标准viewport,需结合window.devicePixelRatio转换DIP: // const widthDip = this.width / window.devicePixelRatio; // const heightDip = this.height / window.devicePixelRatio; // 标准viewport下(<meta name="viewport" content="width=device-width, initial-scale=1">),像素值=DIP值 const widthDip = this.width; const heightDip = this.height; if (widthDip !== 300 || heightDip !== 300) { input.setCustomValidity("必须上传300x300dip的图片"); } else { input.setCustomValidity(""); } // 强制触发WorkWithPlus的验证提示 input.reportValidity(); }; img.src = e.target.result; }; reader.readAsDataURL(input.files[0]); });
- 在字段的
设置验证提示文本
- 在字段的
Validation Error Message属性里填写提示内容(比如“图片尺寸不符,请上传300x300dip的图片”),校验失败时WorkWithPlus会自动弹出该提示
- 在字段的
二、服务端兜底校验(必加)
客户端校验容易被绕过,一定要在服务端补充一层校验:
- 在WorkWithPlus对象的
BeforeSave事件中添加代码:Event BeforeSave &ImageData = YourEntity.ImageField // 替换为你的实体字段名 &Image.Load(&ImageData) &ImgWidth = &Image.Width &ImgHeight = &Image.Height // 标准场景下直接对比像素值即可,若需适配特殊DPI,需结合设备信息计算转换 If &ImgWidth <> 300 Or &ImgHeight <> 300 Msg("图片尺寸必须为300x300dip,请重新上传") Cancel EndIf EndEvent
三、关键注意点
- Viewport设置:确保页面的viewport标签为
<meta name="viewport" content="width=device-width, initial-scale=1">,否则DIP与像素的转换会出错 - 组件版本匹配:确认WorkWithPlus版本与GeneXus 18 Update 11兼容,避免属性缺失或API失效
- 格式限制(可选):若需同时限制图片格式,直接在字段的
Allowed File Types属性中填写image/png,image/jpeg这类值即可
内容的提问来源于stack exchange,提问作者RodrigoLaraH
相关产品推荐
相关产品推荐

