Files
upload/scripts/zip-validate.js

65 lines
2.4 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 提交前校验脚本:压缩包内必须同时包含(doc/docx/pdf)和(ppt/pptx)
// 用法:粘贴到"启用提交前校验"的脚本框中
async function (values, fields, ctx) {
const DOC_EXTS = ['doc', 'docx', 'pdf'];
const PPT_EXTS = ['ppt', 'pptx'];
// 从 zip 原始字节中解析出所有条目文件名(无需解压)
function listZipNames(buf) {
const view = new DataView(buf);
const bytes = new Uint8Array(buf);
const decoder = flag => flag & 0x800 ? new TextDecoder('utf-8') : new TextDecoder('gbk');
const names = [];
let i = 0;
while (i + 4 <= bytes.length) {
// 找本地文件头签名 PK\x03\x04
if (bytes[i] === 0x50 && bytes[i + 1] === 0x4B && bytes[i + 2] === 0x03 && bytes[i + 3] === 0x04) {
if (i + 30 > bytes.length) break;
const nameLen = view.getUint16(i + 26, true);
const extraLen = view.getUint16(i + 28, true);
const flag = view.getUint16(i + 6, true);
if (i + 30 + nameLen > bytes.length) break;
const raw = bytes.subarray(i + 30, i + 30 + nameLen);
let name;
try { name = decoder(flag).decode(raw); } catch (e) { name = new TextDecoder('latin1').decode(raw); }
if (!name.endsWith('/')) names.push(name);
i += 30 + nameLen + extraLen;
} else {
i++;
}
}
return names;
}
const extOf = n => { const p = n.toLowerCase().split('.'); return p.length > 1 ? p.pop() : ''; };
for (const field of fields) {
if (field.type !== 'file') continue;
const file = values[field.name];
if (!file) continue;
const ext = extOf(file.name);
if (ext !== 'zip') continue;
let names;
try {
names = listZipNames(await file.arrayBuffer());
} catch (e) {
return { ok: false, msg: '压缩包读取失败,请重新打包后再上传。' };
}
if (!names.length) {
return { ok: false, msg: '压缩包为空或已损坏,请重新打包后再上传。' };
}
const hasDoc = names.some(n => DOC_EXTS.includes(extOf(n)));
const hasPpt = names.some(n => PPT_EXTS.includes(extOf(n)));
const missing = [];
if (!hasDoc) missing.push('Word 文档(doc/docx)或 PDF');
if (!hasPpt) missing.push('演示文稿(ppt/pptx)');
if (missing.length) {
return { ok: false, msg: `「${file.name}」压缩包内缺少:${missing.join('和')},请检查后重新上传。` };
}
}
return { ok: true };
}