得差不多就是去年的這個時候,我從原來的單位辭職。原因很簡單,二十三四歲,正式一個該奮斗的年紀。雖然家里的條件可以允許自己不必太努力,但是唯有自己擁有賺更多錢的能力,才會讓自己覺得心安。思來想去,選擇了繼續深鉆大學的專業,至此我的前端之路也正式開始了。
這一年,從學習到工作,發生了很多的事情。其實自己是一個比較不愿意寫東西的人,寫博客這個念頭也不是一天倆天了,但就是怎么也開展不了。直到前幾天,公司的一個項目需求,要用百度的編輯器UEditor替換掉原來的富文本編輯器。一個小小的編輯器,做起來卻是一個坑接一個坑,多虧網上的好心的人把自己的經驗留下來,才能順利走下來。感受到這個互聯網的共享性和無私性,我也決定成為大家的其中一員,為大家貢獻出自己踩每一個坑時的心路歷程,希望可以幫助大家,同大家一起共同學習。
話就不多說了,走進正題。UEditor的使用心得。
首先將一下我們的項目架構。本來整個項目是.NET跑的,因為一些原因要轉到JAVA上來,所以目前的項目暫定為.NET來跑前端,接口方面由JAVA來提供。因此在使用UEdior時也是一樣的。
前期還是比較順利的,照著官方文檔來做。
下載的時候,有點小懵逼,本以為就是一個前端小插件,怎么還分這來多版本,鬧啥這是。因為時.net跑的前端,我就下載了.net版
下載的資源包里有demo,還是比較好理解的
簡單的來說就是 1.引倆JS 2.body里加一個script標簽 3.用getEditor方式創建
跑一下。
這是用在一個新聞審核時的編輯器。所以一開始編輯器就會帶有默認值。這里解釋下 我為什么沒有直接直接將數據放在編輯器的script標簽中,如果直接讀那么在編輯器中會顯示一堆字符串而不是轉譯后的html,此外有時還會出現內容展示在編輯器外的bug。
如果通過一個textarea先存放數據再用官方文檔中的setContent()方法設置編輯器的內容,就完美解決了。看下效果,完美。
注:大家在實際使用的時候會遇見雙引號和單引號無法轉譯的問題。這塊我就附個鏈接http://blog.csdn.net/wanghao3616/article/details/25816747 照這樣就可以完美解決了
好了效果實現,重點來了。圖片上傳。我們具體來分析下代碼的流程是怎樣的。
UEdior.all.js這個主文件我們先不看,先看uedior.config.js這個配置的文件
這個紅框的地方就是后臺請求的統一接口。官方文檔已經說了,1.4*版本以后已經把所有的后臺請求接口合并成一個了,也就是說無論上傳還是涂鴉上傳都是使用這個接口只是參數action不一樣。當然我在實際項目的時候還是任性的把這個接口拆開了。
這樣比較直觀。其實比較有用的接口就是前倆個。在調試項目的時候發現,編輯器最先會發這個action='config'的請求。這個是設定圖片訪問規則的一些配置。在寫這個接口的時候出現了一些問題,后端返回的數據老是存在問題,所以我就直接用了項目中基于.net的原始接口調用前端這邊的config.json文件。其實我覺得這個配置文件放在后端調用返回給前端來最好,因為后端最清楚這些請求地址該怎么寫。
因為后端接口沒實現,我就把配置文件放在了前端,之后我把配置中的路徑都設置為空,這一直接憑后端返回的url就可以直接訪問了 不需要再拼了(其實這樣一來,配置沒啥個用了,存粹走個流程。。)
配置讀取完就該上傳圖片了。因為我們的項目是倆個服務器構成的所以呢就涉及到了跨域的問題。。。這里面是有個坑的。那就是單圖和多圖的處理是不一樣的。
多圖比較簡單
只要設置好請求頭之類普通的跨域常見問題,再調剛才設置的圖片上傳接口就OK了
單圖的話就比較蛋疼了。單文件上傳是form提交到iframe,然后iframe里面的內容返回。官方也說了。單文件比較難搞
解決方案就是讓后端先將數據反回給.net服務器的一個中轉頁面,再通過這個中轉頁面返回來顯示,這樣就完美解決了單文件的跨域問題。
單文件的請求接口位置 直接修改all.js
1.修改action就是接口
2.干掉這行默認的url
搞完這個就大功告成了。累累累。。。。。
置于后端代碼。我這個前端er就不貼了 如果有需要的朋友有需要可以留言和我說。
說實在的純手寫這么多,也不知道又沒人會看。第一次,以后也會把質量提起來。自己也會堅持寫下去的。加油各位!!!!!!
ue+ueditor+springboot, 實現word文檔上傳編輯
前言
`前端導入word文檔(doc和docx格式都支持),Ueditor富文本回顯進行二次編輯,目前ueditor項目archived了,實現兩種格式的相關材料相對稀缺。
`解決思路:
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=ue
server.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
文本編輯器實現效果圖:
關注,轉發,私信小編“01”即可獲取Python入門學習資料!
左側編輯區域,右側渲染到HTML顯示效果,除了渲染時候代碼樣式有所不同,其他標題、文字、圖片基本滿足所見即所得的效果
下面講解富文本編輯器在Django項目中如何使用
1、前端頁面引入js文件:
所用編輯器為tinymce.js,引入兩個js文件
2、html代碼布局:
左側編輯區域,右側渲染后預覽區域
下面div左浮動,里面的textarea是富文本編輯區域,注意id要用rich_content,name也要加, {{ content }}是我在提交時候后端返回的數據,方便重新在編輯區域渲染數據
submit通過表單默認的提交方式向后端發post請求傳數據
下面是右側展示的div,右浮動,左右浮動為了更好地對比效果,不用來回滑動滾動條,返回的content其實就是html字符串,我們渲染到瀏覽器即可
3、Django后端代碼
@csrf_exempt是ajax和form表單的post請求csrf解決辦法,如果是form表單的post請求,也可以在form中加{% csrf_token %}
前端是form表單請求,后端只需要根據鍵從表單中讀數據就行,我們的富文本編輯器name屬性值為content,則直接get("content")即可
返回到前端的content,即富文本的html字符串,我們分別在編輯器和右側都進行了渲染,即可見到最開始的效果
本文富文本編輯器僅測試部分常見效果沒有什么問題,另外富文本編輯器也有CKeditor、Ueditor等等,如果大佬們有關于這些的開源demo,也歡迎學習交流
*請認真填寫需求信息,我們會在24小時內與您取得聯系。