如何在TypeScript中读取Zip文件的注释字段?
读取Zip文件注释的实现方案
核心思路
Zip文件的注释字段存放在文件末尾的固定结构里:最后22字节包含中央目录结束标志、注释长度等元数据,紧接着就是注释内容。不需要完整解压,只需读取文件末尾的关键字节段就能解析出注释,完全不用依赖第三方库。
前端JavaScript实现代码
async function getZipComment(file) { // 先读取文件最后22字节,覆盖Zip结尾的核心结构+注释长度字段 const reader = new FileReader(); const blob = file.slice(-22); return new Promise((resolve, reject) => { reader.onload = function(e) { const buffer = new Uint8Array(e.target.result); // 验证是否为有效Zip文件(检查中央目录结束标志:0x504B0506) const signature = (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; if (signature !== 0x504B0506) { resolve(null); return; } // 读取注释长度(第20-21字节,小端序) const commentLength = buffer[20] | (buffer[21] << 8); if (commentLength === 0) { resolve(''); return; } // 读取包含完整注释的末尾字节段 const fullTailReader = new FileReader(); const fullTailBlob = file.slice(-(22 + commentLength)); fullTailReader.onload = function(ee) { const fullBuffer = new Uint8Array(ee.target.result); const commentBytes = fullBuffer.slice(22, 22 + commentLength); // 兼容Zip默认编码CP437和常见的UTF-8 try { resolve(new TextDecoder('utf-8').decode(commentBytes)); } catch { resolve(new TextDecoder('ibm437').decode(commentBytes)); } }; fullTailReader.onerror = reject; fullTailReader.readAsArrayBuffer(fullTailBlob); }; reader.onerror = reject; reader.readAsArrayBuffer(blob); }); } // 使用示例 const fileInput = document.getElementById('zip-input'); fileInput.addEventListener('change', async (e) => { const file = e.target.files[0]; if (!file || !file.name.endsWith('.zip')) return; const comment = await getZipComment(file); console.log('Zip文件注释:', comment); });
关键说明
- 直接操作
File对象的切片读取,无需上传或完整加载文件 - 严格遵循Zip文件格式规范,先验证文件有效性再解析注释
- 处理了编码兼容问题,覆盖Zip规范默认的CP437和常用的UTF-8编码
内容的提问来源于stack exchange,提问作者TheCoolberg
相关产品推荐
相关产品推荐

