You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从字节数组获取文件扩展名:.doc/.docx识别异常求助

问题描述

以下是一段通过字节数组获取文件扩展名的Java代码,依赖tika-core 1.13版本:

public static Map<String, String> getImageType(byte[] imageContent) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        TikaConfig config = TikaConfig.getDefaultConfig();
        MediaType mediaType = config.getMimeRepository().detect(new ByteArrayInputStream(imageContent), new Metadata());
        MimeType mimeType = config.getMimeRepository().forName(mediaType.toString());
        result.put("extn", mimeType.getExtension().replaceFirst(".", ""));
        return result;
    }

这段代码能正确识别.pdf、.jpg、.csv、.txt、.bin、.jpeg等格式,返回对应的扩展名(如{extn=.pdf}),但对.doc和.docx文件无法正常识别,返回空值{extn=}。

问题原因
  1. Tika 1.13属于较旧版本,对Microsoft Office格式的MIME类型与扩展名映射支持不完善:识别.doc时返回application/msword、识别.docx时返回application/vnd.openxmlformats-officedocument.wordprocessingml.document,但该版本中这两类MIME类型未关联对应的扩展名;
  2. 原代码中replaceFirst(".", "")存在正则匹配错误:.在正则中代表任意字符,会错误替换扩展名的第一个字符,而非目标点号。
解决方案

方案1:升级Tika版本(推荐)

将tika-core升级到1.24及以上的稳定版本,新版本完善了Office格式的扩展名映射逻辑,原代码仅需修正正则问题即可正常工作:

public static Map<String, String> getImageType(byte[] imageContent) throws Exception {
        Map<String, String> result = new HashMap<String, String>();
        TikaConfig config = TikaConfig.getDefaultConfig();
        MediaType mediaType = config.getMimeRepository().detect(new ByteArrayInputStream(imageContent), new Metadata());
        MimeType mimeType = config.getMimeRepository().forName(mediaType.toString());
        // 修正正则匹配,转义点号
        result.put("extn", mimeType.getExtension().replaceFirst("\\.", ""));
        return result;
    }

Maven依赖示例:

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>1.28.2</version>
</dependency>

方案2:兼容Tika 1.13版本的手动映射

如果无法升级版本,可手动添加MIME类型到扩展名的映射逻辑:

public static Map<String, String> getImageType(byte[] imageContent) throws Exception {
    Map<String, String> result = new HashMap<String, String>();
    TikaConfig config = TikaConfig.getDefaultConfig();
    MediaType mediaType = config.getMimeRepository().detect(new ByteArrayInputStream(imageContent), new Metadata());
    String mediaTypeStr = mediaType.toString();
    
    String extn;
    switch (mediaTypeStr) {
        case "application/msword":
            extn = "doc";
            break;
        case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
            extn = "docx";
            break;
        default:
            MimeType mimeType = config.getMimeRepository().forName(mediaTypeStr);
            extn = mimeType.getExtension().replaceFirst("\\.", "");
            break;
    }
    
    result.put("extn", extn);
    return result;
}

内容的提问来源于stack exchange,提问作者Ajit Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 00:52:42