首页 » 网站建设 » php版ueditor乱码技巧_Ueditor二次编辑worddoc和docx格式SpringBoot后端

php版ueditor乱码技巧_Ueditor二次编辑worddoc和docx格式SpringBoot后端

访客 2024-11-16 0

扫一扫用手机浏览

文章目录 [+]

序言

`前端导入word文档(doc和docx格式都支持),Ueditor富文本回显进行二次编辑,目前ueditor项目archived了,实现两种格式的干系材料相对稀缺。

php版ueditor乱码技巧_Ueditor二次编辑worddoc和docx格式SpringBoot后端

`办理思路:

php版ueditor乱码技巧_Ueditor二次编辑worddoc和docx格式SpringBoot后端
(图片来自网络侵删)

1.上传word文件

2.后台读取word内容(图片须要额外处理保存到做事器固定的地址,该地址能让浏览器直接访问),天生html文件

3.后台读取html文件内容返回给前端

一、目标

通过上传word文件,通过后台进行解析回显到前端。

二、代码步骤

后端代码构造:

1.maven依赖库

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.15</version></dependency><dependency><groupId>fr.opensagres.xdocreport</groupId><artifactId>org.apache.poi.xwpf.converter.xhtml</artifactId><version>1.0.6</version></dependency>

2.vue页面读取ueditor的配置

代码如下:

/ 获取UE文件上传配置 @param request @param response @throws IOException/@GetMapping(value = "/config")public void ueConfig(HttpServletRequest request, HttpServletResponse response) throws IOException {response.setContentType("application/json");response.setCharacterEncoding("utf-8");String urlPrefix = ueProperties.getSavepath();log.info("urlPrefix = "+urlPrefix);String exec = "{\n" +" / 上传图片配置项 /\n" +" \"imageActionName\": \"catcherImage\", / 实行上传图片的action名称 /\n" +" \"imageFieldName\": \"upfile\", / 提交的图片表单名称 /\n" +" \"imageMaxSize\": 2048, / 上传大小限定,单位B /\n" +" \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], / 上传图片格式显示 /\n" +" \"imageCompressEnable\": true, / 是否压缩图片,默认是true /\n" +" \"imageCompressBorder\": 800, / 图片压缩最长边限定 /\n" +" \"imageInsertAlign\": \"none\", / 插入的图片浮动办法 /\n" +" \"imageUrlPrefix\": \"" + urlPrefix + "\", / 图片访问路径前缀 /\n" +" \"imagePathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", / 上传保存路径,可以自定义保存路径和文件名格式 /\n" +" / {filename} 会更换成原文件名,配置这项须要把稳中文乱码问题 /\n" +" / {rand:6} 会更换成随机数,后面的数字是随机数的位数 /\n" +" / {time} 会更换成韶光戳 /\n" +" / {yyyy} 会更换成四位年份 /\n" +" / {yy} 会更换成两位年份 /\n" +" / {mm} 会更换成两位月份 /\n" +" / {dd} 会更换成两位日期 /\n" +" / {hh} 会更换成两位小时 /\n" +" / {ii} 会更换成两位分钟 /\n" +" / {ss} 会更换成两位秒 /\n" +" / 造孽字符 \\ : ? \" < > | /\n" +" / 具请体看线上文档: fex.baidu.com/ueditor/#use-format_upload_filename /\n" +"\n" +" / 涂鸦图片上传配置项 /\n" +" \"scrawlActionName\": \"uploadscrawl\", / 实行上传涂鸦的action名称 /\n" +" \"scrawlFieldName\": \"upfile\", / 提交的图片表单名称 /\n" +" \"scrawlPathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", / 上传保存路径,可以自定义保存路径和文件名格式 /\n" +" \"scrawlMaxSize\": 2048000, / 上传大小限定,单位B /\n" +" \"scrawlUrlPrefix\": \"\", / 图片访问路径前缀 /\n" +" \"scrawlInsertAlign\": \"none\",\n" +"\n" +" / 截图工具上传 /\n" +" \"snapscreenActionName\": \"uploadimage\", / 实行上传截图的action名称 /\n" +" \"snapscreenPathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", / 上传保存路径,可以自定义保存路径和文件名格式 /\n" +" \"snapscreenUrlPrefix\": \"\", / 图片访问路径前缀 /\n" +" \"snapscreenInsertAlign\": \"none\", / 插入的图片浮动办法 /\n" +"\n" +" / 抓取远程图片配置 /\n" +" \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +" \"catcherActionName\": \"catchimage\", / 实行抓取远程图片的action名称 /\n" +" \"catcherFieldName\": \"source\", / 提交的图片列表表单名称 /\n" +" \"catcherPathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", / 上传保存路径,可以自定义保存路径和文件名格式 /\n" +" \"catcherUrlPrefix\": \"" + urlPrefix + "\", / 图片访问路径前缀 /\n" +" \"catcherMaxSize\": 2048000, / 上传大小限定,单位B /\n" +" \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], / 抓取图片格式显示 /\n" +"\n" +" / 上传视频配置 /\n" +" \"videoActionName\": \"uploadvideo\", / 实行上传视频的action名称 /\n" +" \"videoFieldName\": \"upfile\", / 提交的视频表单名称 /\n" +" \"videoPathFormat\": \"/ueditor/video/{yyyy}{mm}{dd}/\", / 上传保存路径,可以自定义保存路径和文件名格式 /\n" +" \"videoUrlPrefix\": \"\", / 视频访问路径前缀 /\n" +" \"videoMaxSize\": 10240000, / 上传大小限定,单位B,默认10MB /\n" +" \"videoAllowFiles\": [\n" +" \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +" \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"], / 上传视频格式显示 /\n" +" / 上传文件配置 /\n" +" \"fileActionName\": \"uploadfile\", / controller里,实行上传视频的action名称 /\n" +" \"fileFieldName\": \"upfile\", / 提交的文件表单名称 /\n" +" \"filePathFormat\": \"/ueditor/file/{yyyy}{mm}{dd}/\", / 上传保存路径,可以自定义保存路径和文件名格式 /\n" +" \"fileUrlPrefix\": \"\", / 文件访问路径前缀 /\n" +" \"fileMaxSize\": 10240000, / 上传大小限定,单位B,默认10MB /\n" +" \"fileAllowFiles\": [\n" +" \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +" \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +" \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +" \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +" \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +" ], / 上传文件格式显示 /\n" +" / 列出指定目录下的图片 /\n" +" \"imageManagerActionName\": \"listimage\", / 实行图片管理的action名称 /\n" +" \"imageManagerListPath\": \"/ueditor/image/{yyyy}{mm}{dd}/\", / 指定要列出图片的目录 /\n" +" \"imageManagerListSize\": 20, / 每次列出文件数量 /\n" +" \"imageManagerUrlPrefix\": \"" + urlPrefix + "\", / 图片访问路径前缀 /\n" +" \"imageManagerInsertAlign\": \"none\", / 插入的图片浮动办法 /\n" +" \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], / 列出的文件类型 /\n" +" / 列出指定目录下的文件 /\n" +" \"fileManagerActionName\": \"listfile\", / 实行文件管理的action名称 /\n" +" \"fileManagerListPath\": \"/ueditor/file/{yyyy}{mm}{dd}/\", / 指定要列出文件的目录 /\n" +" \"fileManagerUrlPrefix\": \"\", / 文件访问路径前缀 /\n" +" \"fileManagerListSize\": 20, / 每次列出文件数量 /\n" +" \"fileManagerAllowFiles\": [\n" +" \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\",\n" +" \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\",\n" +" \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\",\n" +" \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\",\n" +" \".doc\", \".docx\", \".xls\", \".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"\n" +" ] / 列出的文件类型 /\n" +"}";PrintWriter writer = response.getWriter();writer.write(exec);writer.flush();writer.close();}

```

3.前端导入文件

代码如下:

methods: {ready(editorInstance) { this.editorInstance=editorInstance async uploadWordFile(event) { const file = event.target.files[0]; if (!file) return; // 将Word文件转换为HTML const htmlContent = await this.convertWordToHtml(file); const jsonData = JSON.parse(htmlContent) // 设置UEditor的内容 console.log(jsonData) this.editorInstance.execCommand('inserthtml',jsonData.data)},async convertWordToHtml(wordFile) { // 这里该当是Word文件转HTML的后端接口调用代码 // 假设有一个转换Word为HTML的后端API const formData = new FormData(); formData.append('file', wordFile); const response = await fetch('/api/ue/uploadFile',{ method:'POST', body:formData})if (response.ok) {return await response.text();}throw new Error('转换失落败');}}

4.后端读取文件天生html

代码如下:

/ word文档上传 @param file @return/@PostMapping("/uploadFile")public Object uploadFile(@RequestParam(name = "file") MultipartFile file){ String filename = file.getOriginalFilename(); JSONObject result = new JSONObject(); String visitHtml = ""; try { if (filename.endsWith(".docx")) { //TODO 处理docx格式的 visitHtml = WordConverHtmlUtils.docxToHtmlText(file, ueProperties); } else if (filename.endsWith(".doc")) { //TODO 处理doc格式的 visitHtml = WordConverHtmlUtils.docToHtmlText(file, ueProperties); } else { log.error("不支持的文件格式!
"); } result.put("state", "SUCCESS"); result.put("data", visitHtml); log.info("result: {}", result.toString()); } catch (Exception e) { log.error("文件找不到非常!
"); e.printStackTrace(); } return result;}

5.WordConverHtmlUtils工具类

⚠️⚠️⚠️⚠️⚠️

options.URIResolver(new BasicURIResolver(picUri));

picUri地址,必须能通过浏览器直接访问,否则编辑器中无法渲染出来图片; 比如作者:http://localhost:8000/resource/ueditor/file/20240404/1712220732312.png(本地搭建NG测试)

⚠️⚠️⚠️⚠️⚠️

代码如下:package com.ue.demo.utils;import cn.hutool.core.lang.UUID;import com.ue.demo.config.UeProperties;import lombok.extern.slf4j.Slf4j;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.converter.PicturesManager;import org.apache.poi.hwpf.converter.WordToHtmlConverter;import org.apache.poi.hwpf.usermodel.PictureType;import org.apache.poi.xwpf.converter.core.BasicURIResolver;import org.apache.poi.xwpf.converter.core.FileImageExtractor;import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.springframework.web.multipart.MultipartFile;import org.w3c.dom.Document;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import java.io.;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;/ @author:Peanut @create: 2024-04-05 10:22 @version: 1.0.0 @description:/@Slf4j public class WordConverHtmlUtils { private final static String FILE_URL_PRE = "/ueditor/file/"; / 上传docx文档,返回解析后的Html / public static String docxToHtmlText(MultipartFile file, UeProperties ueProperties) throws Exception { try { String fileName = UUID.fastUUID().toString(); //图片存放地址 String imagePath = ueProperties.getSavepath().concat(FILE_URL_PRE).concat("/"); String fileOutName = imagePath.concat(fileName).concat(".html"); log.info("上传docx文档解析"); log.info("上传docx文档,返回解析后的Html, imagePath:{}", imagePath); log.info("fileOutName:{}", fileOutName); //获取一个用操作Word的工具 XWPFDocument document = new XWPFDocument(file.getInputStream()); //导出为html时的一些基本设置类 XHTMLOptions options = null; //判断word文件中是否有图片 if(document.getAllPictures().size() > 0) { //获取默认的工具,设置缩进indent options = XHTMLOptions.getDefault().indent(4); // 如果包含图片的话,要设置图片的导出位置 File imageFolder = new File(imagePath); //设置图片抽取器的目的地文件夹 用于存放图片文件 options.setExtractor(new FileImageExtractor(imageFolder)); // URI resolver word的html中图片的目录路径 //⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️ //⚠️⚠️⚠️⚠️⚠️ 这里须要设置为前端能过直接访问到的图片地址, 比如作者:http://localhost:8000/resource/ueditor/file/20240404/1712220732312.png, //⚠️⚠️⚠️⚠️⚠️ 否则,ueditor编辑器无法显示word文档中的图片 String picUri = ueProperties.getShowpath().concat(imagePath.substring(imagePath.indexOf("ueditor"))); options.URIResolver(new BasicURIResolver(picUri)); } //获取输出的html文件工具 File outFile = new File(fileOutName); if(!outFile.getParentFile().exists()){ outFile.getParentFile().mkdirs(); } //创建所有的父路径,如果不存在父目录的话 outFile.getParentFile().mkdirs(); //创建一个输出流 OutputStream out = new FileOutputStream(outFile); //html转换器 XHTMLConverter.getInstance().convert(document, out, options); log.info("html转换器 success"); //处理天生的html,字符串形式给前端 return readHtmlStr(fileOutName); } catch (Exception e) { log.error("docxToHtmlText 解析非常", e); } return "";}/ 上传doc格式Word文档,返回解析后的Html @param file @param ueProperties @return @throws Exception/public static String docToHtmlText(MultipartFile file, UeProperties ueProperties) throws Exception { //利用字符数组流获取解析的内容 ByteArrayOutputStream baos = new ByteArrayOutputStream(); OutputStream outStream = new BufferedOutputStream(baos); try { String fileName = UUID.fastUUID().toString(); //将上传的文件传入Document转换 //图片存放地址 String docPath = ueProperties.getSavepath().concat(FILE_URL_PRE).concat("/"); String imagePath = docPath.concat("image/"); String fileOutName = docPath.concat(fileName).concat(".html"); log.info("上传doc文档,返回解析 "); log.info("fileOutName:{}", fileOutName); //创建图片文件的存储目录 new File(imagePath).mkdirs(); //poi中doc文档对应的实体类 HWPFDocument hwpfDocument = new HWPFDocument(file.getInputStream()); //利用空的文档工具构建一个转换工具 WordToHtmlConverter converter = new WordToHtmlConverter(DocumentBuilderFactory .newInstance() .newDocumentBuilder() .newDocument()); //设置存储图片的管理者--利用匿名内部类实现 该类实现了PicturesManager接口,实现了个中的savePicture方法 converter.setPicturesManager(new PicturesManager() { FileOutputStream out = null; //不才面的processDocument方法内部会调用该方法 用于存储word中的图片文件 @Override public String savePicture(byte[] bytes, PictureType pictureType, String name, float width, float height) { try { //单个照片的保存 out = new FileOutputStream(imagePath + name); out.write(bytes); } catch (IOException exception) { exception.printStackTrace(); }finally { if(out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } }}//这里要返回给操作者(HtmlDocumentFacade)一个存储的路径 用于天生Html时定位到图片资源//⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️//⚠️⚠️⚠️⚠️⚠️ 这里须要设置为前端能过直接访问到的图片地址, 比如作者:http://localhost:8000/resource/ueditor/file/20240404/1712220732312.png,//⚠️⚠️⚠️⚠️⚠️ 否则,ueditor编辑器无法显示word文档中的图片return ueProperties.getShowpath().concat(imagePath.substring(imagePath.indexOf("ueditor"))).concat(name); } }); //利用外不雅观模式,将hwpfDocument文档工具设置给HtmlDocumentFacade中的Document属性 converter.processDocument(hwpfDocument); //获取转换器中的document文档 Document htmlDocument = converter.getDocument(); //充当文档工具模型 (DOM) 树形式的转换源树的持有者 -- 源树 DOMSource domSource = new DOMSource(htmlDocument); //转换器 该工具用于将源树转换为结果树 Transformer transformer = TransformerFactory.newInstance().newTransformer(); //设置输出时的以什么办法输出,也可说是结果树的文件类型 可以是html/xml/text或者是一些扩展前三者的扩展类型 transformer.setOutputProperty(OutputKeys.METHOD , "html"); //设置一些必要的属性 设置输出时候的编码为utf-8 transformer.setOutputProperty(OutputKeys.ENCODING , "utf-8"); //转换 将输入的源树转换为结果树并且输出到streamResult中 transformer.transform(domSource , new StreamResult(new File(fileOutName))); log.info("html转换器 success"); //处理天生的html,字符串形式给前端 return readHtmlStr(fileOutName); } catch (Exception e) { log.error("docToHtmlText 非常", e); } finally { baos.close(); outStream.close(); } return null;}/ 读取html文件,转成字符串返回给前端 去除换行,以及连续两个空格 @param htmlDirPath html文件路径 @return @throws IOException/private static String readHtmlStr(String htmlDirPath) throws IOException {log.info("处理天生的html,字符串形式给前端:{} ...Start..", htmlDirPath);String htmlStr = "";try {Path htmlPath = Paths.get(htmlDirPath);htmlStr = new String(Files.readAllBytes(htmlPath));htmlStr = htmlStr.replaceAll("\\n", "");htmlStr = htmlStr.replaceAll("\\s{2,}", " ");log.info("处理天生的html,字符串形式给前端。


end");} catch (IOException e) {log.error("处理天生的html,字符串形式出错了, {}", e.getMessage());}return htmlStr;}}

6.后端配置文件

代码如下:

spring.application.name=ueserver.port=8000##UE编辑器配置#编辑器访问做事器的图片地址ue.showpath=http://localhost:8000/resource#ue文件存储路径前缀ue.savepath=/Users/cookie/Documents/coding/uedemo```!!! ue.showpath=生产上有nginx须要在nginx.conf进行配置

三、实现效果

成功通过导入word文章,回显内容到ueditor编辑器

总结

赠人玫瑰,手留余喷鼻香

源码地址:

https://gitee.com/gwancookie/uedemo

读取word文档天生html借鉴:

https://blog.csdn.net/qq_44717657/article/details/124497326

标签:

相关文章

云浪大数据,驱动未来商业的智能引擎

随着信息技术的飞速发展,大数据已经渗透到我们生活的方方面面,成为推动社会进步的重要力量。云浪大数据,作为我国大数据领域的一匹黑马,...

网站建设 2024-12-17 阅读0 评论0

云盘,新时代存储与共享的智慧选择

随着互联网技术的飞速发展,大数据、云计算等新兴概念逐渐融入人们的生活。在这样的背景下,云盘作为一种新型的存储与共享方式,受到了广泛...

网站建设 2024-12-17 阅读0 评论0

云视通,开启智慧安防新时代的领航者

随着科技的飞速发展,智慧安防逐渐成为社会安全的重要组成部分。云视通作为安防领域的领航者,以其先进的技术、卓越的品质和优质的服务,为...

网站建设 2024-12-17 阅读0 评论0