需判斷上傳檔案為 DOCX 或 ZIP,但兩者副檔名可偽造,且檔案頭(Magic Number)皆為 504B0304(PK 標頭),無法單純靠檔頭區分。
DOCX 本質上是 ZIP 封裝的 XML 結構,必須包含特定內部檔案:
[Content_Types].xmlword/document.xml_rels/.relsimport java.io.File;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public boolean isDocx(File file) {
try (ZipFile zip = new ZipFile(file)) {
// 檢查必要項目是否存在
return zip.getEntry("[Content_Types].xml") != null
&& zip.getEntry("word/document.xml") != null
&& zip.getEntry("_rels/.rels") != null;
} catch (IOException e) {
return false; // 非合法 ZIP 或讀取失敗
}
}
[Content_Types].xml 確認 Content-Type 包含 application/vnd.openxmlformats-officedocument.wordprocessingml.document。word/document.xml 命名空間為 https://schemas.openxmlformats.org/wordprocessingml/2006/main。僅讀取 ZIP 目錄項目(Central Directory),不解壓內容,極快且記憶體占用極低。若須處理大量檔案,可先以檔頭快速過濾非 ZIP 檔,再對疑似 ZIP 檔執行上述檢查。