如何设置<input type="file">控件仅允许上传Lottie格式文件
Lottie文件上传input标签配置方案
基础配置(仅靠HTML属性实现初步过滤)
Lottie文件常见两种格式:.json格式的标准Lottie动画文件、.lottie后缀的打包专用格式,直接给input标签设置accept属性即可实现系统文件选择窗口的默认过滤:<input type="file" accept=".json,.lottie,application/json,application/x-lottie">注意:
accept属性仅做前端展示层过滤,用户可手动调整文件选择器的过滤选项选中其他格式文件,无法完全限制上传。新增前端选中后校验(进一步限制非法文件)
监听input的change事件,在用户选中文件后校验文件后缀,还可对JSON格式的文件额外校验核心字段确认是合法Lottie文件:const fileInput = document.querySelector('input[type="file"]'); fileInput.addEventListener('change', (e) => { const selectedFile = e.target.files[0]; if (!selectedFile) return; // 校验文件后缀 const allowedSuffix = ['.json', '.lottie']; const fileSuffix = selectedFile.name.slice(selectedFile.name.lastIndexOf('.')).toLowerCase(); if (!allowedSuffix.includes(fileSuffix)) { alert('仅支持上传Lottie格式文件(.json/.lottie)'); fileInput.value = ''; // 清空错误选中 return; } // 可选:校验JSON格式Lottie的核心字段 if (fileSuffix === '.json') { const reader = new FileReader(); reader.onload = (event) => { try { const lottieContent = JSON.parse(event.target.result); // 检查Lottie必备的版本、帧率、图层等核心字段 if (!lottieContent.v || !lottieContent.fr || !Array.isArray(lottieContent.layers)) { alert('所选JSON文件不是合法的Lottie动画文件'); fileInput.value = ''; } } catch (err) { alert('所选JSON文件格式损坏'); fileInput.value = ''; } }; reader.readAsText(selectedFile); } });补充后端校验
前端所有校验逻辑都可被绕过,后端接收到文件后需要同样做后缀、文件结构校验,避免非法文件上传到服务端。
内容的提问来源于stack exchange,提问作者Darshan
相关产品推荐
相关产品推荐

