Tika

前端页面调用 tika-server

下载 tika-server

/images/posts/Tika/1.png
(图1)

运行

注意一定要加 --host=0.0.0.0,否则调不通

cmd
1
2
3
chcp 65001

java -jar tika-server-standard-2.9.2.jar --host=0.0.0.0

前端页面调用

实现功能:批量将文件夹内的文件转为文本文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>tika</title>
</head>

<body>
    <input type="file" name="files" id="folderInput" webkitdirectory multiple>
    <button onclick="upload()">上传</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
    <script>
        async function upload() {
            //根据id获取元素
            const inputElement = document.getElementById('folderInput');
            const files = inputElement.files;

            var txtName = '' //文件名字

            if (files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    var fileName = files[i].name
                    fileName = fileName.substring(0, fileName.lastIndexOf("."))

                    //发送请求
                    await fetch('http://127.0.0.1:9998/tika', {
                        method: 'PUT',
                        headers: {
                            // 'accept': 'text/plain',
                            // 'accept': 'application/json',
                            'Content-Type': 'application/octet-stream',
                        },
                        body: files[i]
                    }).then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok');
                        }
                        return response.text();
                    }).then(data => {
                        var blob = new Blob([data], { type: 'text/plain' });
                        var link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);

                        link.download = fileName + '.txt';
                        fileName = ''  //使用过后记得清空

                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(link.href); // 清理blob URL,避免内存泄露

                    }).catch(error => {
                        alert("上传出错: " + error.message);
                    });
                }
            }
        }
    </script>
</body>

</html>

请求头的几种情况

获取文件文本
1
2
3
4
headers: {
    'accept': 'text/plain',
    'Content-Type': 'application/octet-stream',
}
获取文件元数据
1
2
3
4
headers: {
    'accept': 'application/json',
    'Content-Type': 'application/octet-stream',
}
获取文件文本和元数据
1
2
3
4
5
`tika-server 3.0` 之前的版本,有些格式的文件会解析不出来文本内容,只会解析出来元数据

headers: {
    'Content-Type': 'application/octet-stream',
}

跨域问题

1
2
3
4
Access to fetch at 'http://127.0.0.1:9998/tika' from origin 'http://127.0.0.1:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
text.html:30 
        
PUT http://127.0.0.1:9998/tika net::ERR_FAILED

尽管网页和服务都运行在同一台机器上(即使用相同的IP地址 127.0.0.1),但它们通过不同的端口(80819998)进行通信,这仍然被视为跨源(CORS,Cross-Origin Resource Sharing)请求。在 Web 安全中,CORS 策略用于限制哪些外部网站可以访问你的资源。即使两个资源都在同一台机器上,只要端口不同,它们就被视为不同的源。

当使用 Postman 或类似的 API 测试工具(如 cURL)能够成功访问 http://127.0.0.1:9998/tika 而浏览器却因为 CORS 策略阻止访问时,原因主要在于 CORS 策略是浏览器安全功能的一部分,它限制了从脚本(如通过 <script>标签AJAX调用 等)发起的跨源 HTTP 请求。

PostmancURL 等工具不是浏览器,它们不受浏览器安全策略(如 CORS)的限制。这些工具直接向服务器发送 HTTP 请求,并接收服务器的响应,而不会检查或应用 CORS 策略。

解决方法:下载浏览器插件(如 CORS Unblock)来临时禁用 CORS 检查。但请注意,这种方法仅适用于开发环境,并且不应在生产环境中使用。

/images/posts/Tika/2.png
(图2)

TikaOCR

参考地址:https://cwiki.apache.org/confluence/display/TIKA/TikaOCR

/images/posts/Tika/3.png
(图3)
/images/posts/Tika/4.png
(图4)

安装 Tesseract-OCR

配置环境变量

安装 ImageMagick

7.0 版本和 6.x 版本有些不同,系统环境变量都是自动配置好的,不需要手动配置

配置 tika-server

下载 tika-server-standard-2.9.2.jar

/images/posts/Tika/5.png
(图5)

修改 tika-server-standard-2.9.2.jar 中的 tika-server-config-default.xml 文件

/images/posts/Tika/6.png
(图6)
tika-server-config-default.xml
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<properties>
  <parsers>
    <parser class="org.apache.tika.parser.ocr.TesseractOCRParser">
      <params>
        <!-- these are the defaults; you only need to specify the ones you want
             to modify -->
        <param name="applyRotation" type="bool">false</param>
        <param name="colorSpace" type="string">gray</param>
        <param name="density" type="int">300</param>
        <param name="depth" type="int">4</param>
        <param name="enableImagePreprocessing" type="bool">false</param>
        <param name="filter" type="string">triangle</param>
        <param name="imageMagickPath" type="string">D:\ImageMagick</param>
        <param name="language" type="string">eng</param>
        <param name="maxFileSizeToOcr" type="long">2147483647</param>
        <param name="minFileSizeToOcr" type="long">0</param>
        <param name="pageSegMode" type="string">1</param>
        <param name="pageSeparator" type="string"></param>
        <param name="preserveInterwordSpacing" type="bool">false</param>
        <param name="resize" type="int">200</param>
        <param name="skipOcr" type="bool">false</param>
        <param name="tessdataPath" type="string">D:\Tesseract-OCR\tessdata</param>
        <param name="tesseractPath" type="string">D:\Tesseract-OCR</param>
        <param name="timeoutSeconds" type="int">120</param>
      </params>
    </parser>
  </parsers>
</properties>

解析文件中的图片

大部分的文件格式都可以

1
curl -T testOCR.pdf http://localhost:9998/rmeta/text --header "X-Tika-PDFextractInlineImages: true" --header "X-Tika-OCRLanguage: chi_sim"

如果图片中的文字是竖排,做以下更改

1
curl -T testOCR.pdf http://localhost:9998/rmeta/text --header "X-Tika-PDFextractInlineImages: true" --header "X-Tika-OCRLanguage: chi_sim+chi_sim_vert"

引用外部的配置文件

原来:解压 jar 包,修改配置文件,重新压缩为 jar 包,非常麻烦,所以我们需要使用引用外部配置文件的方式
现在:复制配置文件到外部,在外部修改后,启动 jar 包时引用外部的配置文件

无效的方式

  • 将配置文件复制到 jar 包同一层级,通过 --config=tika-server-config-default.xml 引用

正确方式

  • 方式一:将配置文件复制到 jar 包同一层级,直接 java -jar tika-server-standard-2.9.2.jar 启动
  • 方式二:在 jar 包的同一层级创建 config 目录,将配置文件复制到 config 目录中,直接 java -jar tika-server-standard-2.9.2.jar 启动
解释
  • 方式一:同目录下的配置文件优先级要高于 jar 包中的配置文件
  • 方式二:config 文件加下配置文件优先级要高于 jar 包目录下的配置文件

0%