营养科普富文本图片链接处理

This commit is contained in:
sxu 2025-05-13 17:15:30 +08:00
parent 0ad1b05338
commit b5bc095e7e
2 changed files with 21 additions and 38 deletions

View File

@ -198,6 +198,12 @@
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.17.2</version> <!-- 检查最新版本 -->
</dependency>
<dependency>
<groupId>com.arcsoft.face</groupId>
<artifactId>arcsoft-sdk-face</artifactId>

View File

@ -1,15 +1,11 @@
package com.bonus.canteen.core.common.utils;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import lombok.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.function.Function;
public class RichTextUtil {
@ -17,42 +13,23 @@ public class RichTextUtil {
private static final Logger log = LoggerFactory.getLogger(RichTextUtil.class);
public static String getCutFileUrl(String richText) {
return parseXml(richText, FileUrlUtil::getFileUrl);
return parseXml(richText);
}
private static String parseXml(String richText, Function<String, String> method) {
if (StrUtil.isBlank(richText)) {
return richText;
} else {
try {
Document document = XmlUtil.parseXml(richText);
processHtml(document.getDocumentElement(), method);
richText = XmlUtil.toStr(document, "UTF-8", false, true);
} catch (Exception e) {
log.error("{}解析富文本错误:{}", new Object[]{richText, e.getMessage(), e});
}
private static String parseXml(String richText) {
// 1. 解析 HTML
Document doc = Jsoup.parse(richText);
return richText;
}
}
private static void processHtml(Element element, Function<String, String> method) {
NodeList children = element.getChildNodes();
for(int i = 0; i < children.getLength(); ++i) {
Node node = children.item(i);
if (node instanceof Element) {
Element child = (Element) node;
if ("img".equalsIgnoreCase(child.getNodeName())) {
String oldSrc = child.getAttribute("src");
String newSrc = (String)method.apply(oldSrc);
child.setAttribute("src", newSrc);
}
processHtml(child, method);
}
// 2. 遍历所有 <img> 标签并修改 src
for (Element img : doc.select("img")) {
String originalSrc = img.attr("src");
img.attr("src", FileUrlUtil.getFileUrl(originalSrc));
}
// 3. 获取处理后的 HTML
String processedText = doc.body().html();
return processedText;
}
}