篇文章給大家?guī)?lái)的內(nèi)容是關(guān)于微信小程序如何調(diào)用后臺(tái)service(圖文教程),有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對(duì)你有所幫助。
寫(xiě)在前頭,本篇文章簡(jiǎn)單記錄一下,在前后端分離的微信小程序應(yīng)用中,前端訪問(wèn)后臺(tái)service的實(shí)現(xiàn)思路,沒(méi)有過(guò)多涉及技術(shù)實(shí)現(xiàn)方面。
先上一張官網(wǎng)的圖片,它很清楚的講明了要在后臺(tái)service為每一個(gè)小程序用戶提供登錄信息需要做哪些事情。用戶拿到了后臺(tái)給的登錄憑據(jù),訪問(wèn)后臺(tái)service。
靜默授權(quán)與非靜默授權(quán)
先來(lái)講講這兩個(gè)概念,靜默授權(quán),顧名思義,這授權(quán)動(dòng)作對(duì)于用戶來(lái)說(shuō)是感知不到的,小程序端悄咪咪得就做了。因此,沒(méi)有知會(huì)用戶的授權(quán)方式拿到的信息也是不太重要的。但是,靜默授權(quán)是開(kāi)始重要的一步,因?yàn)樗鼮榻酉聛?lái)的動(dòng)作提供了code。調(diào)用靜默授權(quán)可用小程序提供的API:wx.login()。再來(lái)講講非靜默授權(quán),顧名思義,它的授權(quán)是要有明顯動(dòng)靜的,而且它是要得到用戶認(rèn)可才可以執(zhí)行。API:wx.getUserInfo(),這個(gè)接口要不要用可根據(jù)小程序的實(shí)際需求來(lái)。
后臺(tái)獲取openId
小程序提供了一個(gè)接口code2session,拿著我們靜默授權(quán)獲取到的臨時(shí)登錄憑證code再調(diào)用一下這個(gè)接口就能獲取到openId了。openId是在當(dāng)前小程序中對(duì)用戶唯一性的標(biāo)識(shí)。注意,這一步是在后臺(tái)服務(wù)器做的,我們參考一下官網(wǎng)的文檔(后端API)就會(huì)更清楚了。它說(shuō):
后端API不能直接在小程序內(nèi)通過(guò)wx.request調(diào)用,即api.weixin.qq.com不能被配置為服務(wù)器域名。
但是我們會(huì)有疑問(wèn),我們?cè)谧约洪_(kāi)發(fā)的時(shí)候,在小程序端調(diào)用是success的,和官網(wǎng)說(shuō)的并不一樣。如果你碰到和我一樣的疑問(wèn)可以看看這個(gè)(重點(diǎn)在4.4.2服務(wù)器接口)。
基于OAuth2.0生成token
在后臺(tái),可以用SpringSecurity的OAuth2.0這一個(gè)工具,用openId來(lái)生成前端請(qǐng)求后端數(shù)據(jù)的附帶校驗(yàn)信息token。具體是如何實(shí)現(xiàn)的筆者也沒(méi)有深入了解……獲取到了這個(gè)token后,前端可將其存入webStorage中,每一次調(diào)用后臺(tái)service的時(shí)候,就可以利用請(qǐng)求的攔截器在config參數(shù)中加入token。后端就可以確定發(fā)送請(qǐng)求的用戶身份,保證了系統(tǒng)的安全性。
總結(jié):以上大致描繪了小程序后臺(tái)自定義登錄態(tài)的開(kāi)發(fā)思路。
本文參考:微信小程序開(kāi)發(fā)基礎(chǔ)教程 https://www.html.cn/study/20.html
以上就是微信小程序如何調(diào)用后臺(tái)service(圖文教程)的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注其它相關(guān)文章!
更多技巧請(qǐng)《轉(zhuǎn)發(fā) + 關(guān)注》哦!
ue+ueditor+springboot, 實(shí)現(xiàn)word文檔上傳編輯
前言
`前端導(dǎo)入word文檔(doc和docx格式都支持),Ueditor富文本回顯進(jìn)行二次編輯,目前ueditor項(xiàng)目archived了,實(shí)現(xiàn)兩種格式的相關(guān)材料相對(duì)稀缺。
`解決思路:
1.上傳word文件
2.后臺(tái)讀取word內(nèi)容(圖片需要額外處理保存到服務(wù)器固定的地址,該地址能讓瀏覽器直接訪問(wèn)),生成html文件
3.后臺(tái)讀取html文件內(nèi)容返回給前端
一、目標(biāo)
通過(guò)上傳word文件,通過(guò)后臺(tái)進(jìn)行解析回顯到前端。
二、代碼步驟
后端代碼結(jié)構(gòu):
1.maven依賴庫(kù)
<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頁(yè)面讀取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" +
" /* 上傳圖片配置項(xiàng) */\n" +
" \"imageActionName\": \"catcherImage\", /* 執(zhí)行上傳圖片的action名稱 */\n" +
" \"imageFieldName\": \"upfile\", /* 提交的圖片表單名稱 */\n" +
" \"imageMaxSize\": 2048, /* 上傳大小限制,單位B */\n" +
" \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], /* 上傳圖片格式顯示 */\n" +
" \"imageCompressEnable\": true, /* 是否壓縮圖片,默認(rèn)是true */\n" +
" \"imageCompressBorder\": 800, /* 圖片壓縮最長(zhǎng)邊限制 */\n" +
" \"imageInsertAlign\": \"none\", /* 插入的圖片浮動(dòng)方式 */\n" +
" \"imageUrlPrefix\": \"" + urlPrefix + "\", /* 圖片訪問(wèn)路徑前綴 */\n" +
" \"imagePathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */\n" +
" /* {filename} 會(huì)替換成原文件名,配置這項(xiàng)需要注意中文亂碼問(wèn)題 */\n" +
" /* {rand:6} 會(huì)替換成隨機(jī)數(shù),后面的數(shù)字是隨機(jī)數(shù)的位數(shù) */\n" +
" /* {time} 會(huì)替換成時(shí)間戳 */\n" +
" /* {yyyy} 會(huì)替換成四位年份 */\n" +
" /* {yy} 會(huì)替換成兩位年份 */\n" +
" /* {mm} 會(huì)替換成兩位月份 */\n" +
" /* {dd} 會(huì)替換成兩位日期 */\n" +
" /* {hh} 會(huì)替換成兩位小時(shí) */\n" +
" /* {ii} 會(huì)替換成兩位分鐘 */\n" +
" /* {ss} 會(huì)替換成兩位秒 */\n" +
" /* 非法字符 \\ : * ? \" < > | */\n" +
" /* 具請(qǐng)?bào)w看線上文檔: fex.baidu.com/ueditor/#use-format_upload_filename */\n" +
"\n" +
" /* 涂鴉圖片上傳配置項(xiàng) */\n" +
" \"scrawlActionName\": \"uploadscrawl\", /* 執(zhí)行上傳涂鴉的action名稱 */\n" +
" \"scrawlFieldName\": \"upfile\", /* 提交的圖片表單名稱 */\n" +
" \"scrawlPathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */\n" +
" \"scrawlMaxSize\": 2048000, /* 上傳大小限制,單位B */\n" +
" \"scrawlUrlPrefix\": \"\", /* 圖片訪問(wèn)路徑前綴 */\n" +
" \"scrawlInsertAlign\": \"none\",\n" +
"\n" +
" /* 截圖工具上傳 */\n" +
" \"snapscreenActionName\": \"uploadimage\", /* 執(zhí)行上傳截圖的action名稱 */\n" +
" \"snapscreenPathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */\n" +
" \"snapscreenUrlPrefix\": \"\", /* 圖片訪問(wèn)路徑前綴 */\n" +
" \"snapscreenInsertAlign\": \"none\", /* 插入的圖片浮動(dòng)方式 */\n" +
"\n" +
" /* 抓取遠(yuǎn)程圖片配置 */\n" +
" \"catcherLocalDomain\": [\"127.0.0.1\", \"localhost\", \"img.baidu.com\"],\n" +
" \"catcherActionName\": \"catchimage\", /* 執(zhí)行抓取遠(yuǎn)程圖片的action名稱 */\n" +
" \"catcherFieldName\": \"source\", /* 提交的圖片列表表單名稱 */\n" +
" \"catcherPathFormat\": \"/ueditor/image/{yyyy}{mm}{dd}/\", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */\n" +
" \"catcherUrlPrefix\": \"" + urlPrefix + "\", /* 圖片訪問(wèn)路徑前綴 */\n" +
" \"catcherMaxSize\": 2048000, /* 上傳大小限制,單位B */\n" +
" \"catcherAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], /* 抓取圖片格式顯示 */\n" +
"\n" +
" /* 上傳視頻配置 */\n" +
" \"videoActionName\": \"uploadvideo\", /* 執(zhí)行上傳視頻的action名稱 */\n" +
" \"videoFieldName\": \"upfile\", /* 提交的視頻表單名稱 */\n" +
" \"videoPathFormat\": \"/ueditor/video/{yyyy}{mm}{dd}/\", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */\n" +
" \"videoUrlPrefix\": \"\", /* 視頻訪問(wèn)路徑前綴 */\n" +
" \"videoMaxSize\": 10240000, /* 上傳大小限制,單位B,默認(rèn)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里,執(zhí)行上傳視頻的action名稱 */\n" +
" \"fileFieldName\": \"upfile\", /* 提交的文件表單名稱 */\n" +
" \"filePathFormat\": \"/ueditor/file/{yyyy}{mm}{dd}/\", /* 上傳保存路徑,可以自定義保存路徑和文件名格式 */\n" +
" \"fileUrlPrefix\": \"\", /* 文件訪問(wèn)路徑前綴 */\n" +
" \"fileMaxSize\": 10240000, /* 上傳大小限制,單位B,默認(rèn)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\", /* 執(zhí)行圖片管理的action名稱 */\n" +
" \"imageManagerListPath\": \"/ueditor/image/{yyyy}{mm}{dd}/\", /* 指定要列出圖片的目錄 */\n" +
" \"imageManagerListSize\": 20, /* 每次列出文件數(shù)量 */\n" +
" \"imageManagerUrlPrefix\": \"" + urlPrefix + "\", /* 圖片訪問(wèn)路徑前綴 */\n" +
" \"imageManagerInsertAlign\": \"none\", /* 插入的圖片浮動(dòng)方式 */\n" +
" \"imageManagerAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], /* 列出的文件類型 */\n" +
" /* 列出指定目錄下的文件 */\n" +
" \"fileManagerActionName\": \"listfile\", /* 執(zhí)行文件管理的action名稱 */\n" +
" \"fileManagerListPath\": \"/ueditor/file/{yyyy}{mm}{dd}/\", /* 指定要列出文件的目錄 */\n" +
" \"fileManagerUrlPrefix\": \"\", /* 文件訪問(wèn)路徑前綴 */\n" +
" \"fileManagerListSize\": 20, /* 每次列出文件數(shù)量 */\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.前端導(dǎo)入文件
代碼如下:
methods: {
ready(editorInstance) {
this.editorInstance=editorInstance
async uploadWordFile(event) {
const file=event.target.files[0];
if (!file) return;
// 將Word文件轉(zhuǎn)換為HTML
const htmlContent=await this.convertWordToHtml(file);
const jsonData=JSON.parse(htmlContent)
// 設(shè)置UEditor的內(nèi)容
console.log(jsonData)
this.editorInstance.execCommand('inserthtml',jsonData.data)
},
async convertWordToHtml(wordFile) {
// 這里應(yīng)該是Word文件轉(zhuǎn)HTML的后端接口調(diào)用代碼
// 假設(shè)有一個(gè)轉(zhuǎn)換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('轉(zhuǎn)換失敗');
}
}
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地址,必須能通過(guò)瀏覽器直接訪問(wèn),否則編輯器中無(wú)法渲染出來(lái)圖片; 比如作者:http://localhost:8000/resource/ueditor/file/20240404/1712220732312.png(本地搭建NG測(cè)試)
??????????
代碼如下:
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);
//獲取一個(gè)用操作Word的對(duì)象
XWPFDocument document=new XWPFDocument(file.getInputStream());
//導(dǎo)出為html時(shí)的一些基本設(shè)置類
XHTMLOptions options=null;
//判斷word文件中是否有圖片
if(document.getAllPictures().size() > 0) {
//獲取默認(rèn)的對(duì)象,設(shè)置縮進(jìn)indent
options=XHTMLOptions.getDefault().indent(4);
// 如果包含圖片的話,要設(shè)置圖片的導(dǎo)出位置
File imageFolder=new File(imagePath);
//設(shè)置圖片抽取器的目的地文件夾 用于存放圖片文件
options.setExtractor(new FileImageExtractor(imageFolder));
// URI resolver word的html中圖片的目錄路徑
//??????????????????????????????????
//?????????? 這里需要設(shè)置為前端能過(guò)直接訪問(wèn)到的圖片地址, 比如作者:http://localhost:8000/resource/ueditor/file/20240404/1712220732312.png,
//?????????? 否則,ueditor編輯器無(wú)法顯示word文檔中的圖片
String picUri=ueProperties.getShowpath().concat(imagePath.substring(imagePath.indexOf("ueditor")));
options.URIResolver(new BasicURIResolver(picUri));
}
//獲取輸出的html文件對(duì)象
File outFile=new File(fileOutName);
if(!outFile.getParentFile().exists()){
outFile.getParentFile().mkdirs();
}
//創(chuàng)建所有的父路徑,如果不存在父目錄的話
outFile.getParentFile().mkdirs();
//創(chuàng)建一個(gè)輸出流
OutputStream out=new FileOutputStream(outFile);
//html轉(zhuǎn)換器
XHTMLConverter.getInstance().convert(document, out, options);
log.info("html轉(zhuǎn)換器 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 {
//使用字符數(shù)組流獲取解析的內(nèi)容
ByteArrayOutputStream baos=new ByteArrayOutputStream();
OutputStream outStream=new BufferedOutputStream(baos);
try {
String fileName=UUID.fastUUID().toString();
//將上傳的文件傳入Document轉(zhuǎn)換
//圖片存放地址
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);
//創(chuàng)建圖片文件的存儲(chǔ)目錄
new File(imagePath).mkdirs();
//poi中doc文檔對(duì)應(yīng)的實(shí)體類
HWPFDocument hwpfDocument=new HWPFDocument(file.getInputStream());
//使用空的文檔對(duì)象構(gòu)建一個(gè)轉(zhuǎn)換對(duì)象
WordToHtmlConverter converter=new WordToHtmlConverter(DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.newDocument());
//設(shè)置存儲(chǔ)圖片的管理者--使用匿名內(nèi)部類實(shí)現(xiàn) 該類實(shí)現(xiàn)了PicturesManager接口,實(shí)現(xiàn)了其中的savePicture方法
converter.setPicturesManager(new PicturesManager() {
FileOutputStream out=null;
//在下面的processDocument方法內(nèi)部會(huì)調(diào)用該方法 用于存儲(chǔ)word中的圖片文件
@Override
public String savePicture(byte[] bytes, PictureType pictureType, String name, float width, float height) {
try {
//單個(gè)照片的保存
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)一個(gè)存儲(chǔ)的路徑 用于生成Html時(shí)定位到圖片資源
//??????????????????????????????????
//?????????? 這里需要設(shè)置為前端能過(guò)直接訪問(wèn)到的圖片地址, 比如作者:http://localhost:8000/resource/ueditor/file/20240404/1712220732312.png,
//?????????? 否則,ueditor編輯器無(wú)法顯示word文檔中的圖片
return ueProperties.getShowpath().concat(imagePath.substring(imagePath.indexOf("ueditor"))).concat(name);
}
});
//使用外觀模式,將hwpfDocument文檔對(duì)象設(shè)置給HtmlDocumentFacade中的Document屬性
converter.processDocument(hwpfDocument);
//獲取轉(zhuǎn)換器中的document文檔
Document htmlDocument=converter.getDocument();
//充當(dāng)文檔對(duì)象模型 (DOM) 樹(shù)形式的轉(zhuǎn)換源樹(shù)的持有者 -- 源樹(shù)
DOMSource domSource=new DOMSource(htmlDocument);
//轉(zhuǎn)換器 該對(duì)象用于將源樹(shù)轉(zhuǎn)換為結(jié)果樹(shù)
Transformer transformer=TransformerFactory.newInstance().newTransformer();
//設(shè)置輸出時(shí)的以什么方式輸出,也可說(shuō)是結(jié)果樹(shù)的文件類型 可以是html/xml/text或者是一些擴(kuò)展前三者的擴(kuò)展類型
transformer.setOutputProperty(OutputKeys.METHOD , "html");
//設(shè)置一些必要的屬性 設(shè)置輸出時(shí)候的編碼為utf-8
transformer.setOutputProperty(OutputKeys.ENCODING , "utf-8");
//轉(zhuǎn)換 將輸入的源樹(shù)轉(zhuǎn)換為結(jié)果樹(shù)并且輸出到streamResult中
transformer.transform(domSource , new StreamResult(new File(fileOutName)));
log.info("html轉(zhuǎn)換器 success");
//處理生成的html,字符串形式給前端
return readHtmlStr(fileOutName);
} catch (Exception e) {
log.error("docToHtmlText 異常", e);
} finally {
baos.close();
outStream.close();
}
return null;
}
/**
* 讀取html文件,轉(zhuǎn)成字符串返回給前端
* 去除換行,以及連續(xù)兩個(gè)空格
* @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,字符串形式出錯(cuò)了, {}", e.getMessage());
}
return htmlStr;
}
}
6.后端配置文件
代碼如下:
spring.application.name=ue
server.port=8000
##UE編輯器配置
#編輯器訪問(wèn)服務(wù)器的圖片地址
ue.showpath=http://localhost:8000/resource
#ue文件存儲(chǔ)路徑前綴
ue.savepath=/Users/cookie/Documents/coding/uedemo
```
!!! ue.showpath=生產(chǎn)上有nginx需要在nginx.conf進(jìn)行配置
三、實(shí)現(xiàn)效果
成功通過(guò)導(dǎo)入word文章,回顯內(nèi)容到ueditor編輯器
總結(jié)
*贈(zèng)人玫瑰,手留余香*
源碼地址:
https://gitee.com/gwancookie/uedemo
**讀取word文檔生成html借鑒:**
https://blog.csdn.net/qq_44717657/article/details/124497326
天給大家推薦一款超不錯(cuò)的CMS內(nèi)容管理系統(tǒng)DoraCMS-Admin。
dora-cms 基于vue.js+eggjs+express+mongodb構(gòu)建的一套后臺(tái)CMS管理系統(tǒng),star高達(dá)2.8K+。結(jié)構(gòu)簡(jiǎn)單、易于拓展,非常適合進(jìn)行二次開(kāi)發(fā)。
{% header adaptor="default" %}
<!-- 模板靜態(tài)資源 -->
{% assets 'base.css index.css media.css swiper.min.css list.css swiper.min.js' %}
{% endassets %}
<!-- 二次開(kāi)發(fā)靜態(tài)資源 -->
{% assets 'dora.front.js white.css' %}
{% endassets %}
{% endheader %}
{% recommend pageSize=3 %}
{% for item in recommend %}
<li><a href="{{item.url}}" target="_blank">{{item.stitle}}</a></li>
{% endfor %}
{% hottags pageSize=15 %}
{% for tagItem in hottags %}
<li><a href="{{tagItem.url}}">{{tagItem.name}}</a></li>
{% endfor %}
更多的模板調(diào)用這里不詳細(xì)介紹了,大家可以去查看下面的文檔。
https://www.doracms.com/frontend/showdata/
目前市面上有很多內(nèi)容管理系統(tǒng)(如織夢(mèng)CMS、帝國(guó)等),都是以php開(kāi)發(fā)為主,而DoraCMS 則是基于nodejs,只要有一些前端開(kāi)發(fā)基礎(chǔ),很快就能上手。而且DoraCMS完全開(kāi)源,你可以自由定制屬于自己的網(wǎng)站內(nèi)容管理平臺(tái)。
end,附上項(xiàng)目地址鏈接。
# 文檔地址
https://www.doracms.com/
# 倉(cāng)庫(kù)地址
https://github.com/doramart/DoraCMS/
好了,今天就分享到這里。如果感興趣可以去看看,希望對(duì)大家有所幫助哈!
*請(qǐng)認(rèn)真填寫(xiě)需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。