WangEditor 富文本編輯器是一款輕量、簡潔、易用、開源免費的編輯器
WangEditor 官網:https://www.wangeditor.com/
WangEditor富文本編輯器的導入
-
HTML部分
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://unpkg.com/wangeditor/dist/wangEditor.min.js"></script>
WangEditor富文本編輯器的使用
-
HTML部分
<div id="editor"></div> <textarea style="display: none" name="blogContent" id="blogContent"></textarea>
-
JavaScript部分
<!-- wangEditor 富文本編輯器 js --> <script type="text/javascript"> var E = window.wangEditor; var editor = new E('#editor'); // 獲取wangEditor中的內容 var blogContent = $('#blogContent'); // 監控wangEditor中的內容變化,並將html內容同步更新到 textarea editor.config.onchange = function (newHtml) { blogContent.val(newHtml); }; editor.config.uploadImgServer = '[[@{/user/upload}]]'; // 文件上傳接口 editor.config.uploadImgMaxSize = 5 * 1024 * 1024; // 文件大小5M editor.config.uploadImgMaxLength = 9; editor.config.uploadFileName = 'files'; editor.config.uploadImgHooks = { success: function (xhr, editor, result) { console.log("上傳成功"); }, fail: function (xhr, editor, result) { console.log("上傳失敗,原因是" + result); }, error: function (xhr, editor) { console.log("上傳出錯"); }, customInsert: function(insertImgFn, result) { // 圖片上傳並返回結果 var url = result.url; insertImgFn(url); } } editor.create(); // 初始化 textarea 的值 blogContent.val(editor.txt.html()); </script>
-
Controller部分 文件上傳接口
// 上傳文件 @ResponseBody @RequestMapping("/upload") public String fileUpload(@RequestParam("files") MultipartFile files) throws IOException { // // win系統 上傳路徑保存設置 // // 獲取項目路徑 // File projectPath = new File(ResourceUtils.getURL("classpath:").getPath()); // // 絕對路徑=項目路徑+自定義路徑 // File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/"); // if (!pathFile.exists()) { // pathFile.mkdirs(); // } // //上傳文件地址 // UUID uuid = UUID.randomUUID(); // File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename()); // files.transferTo(serverFile); // // String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/"); // // return imgPath; // Linux服務器 上傳路徑保存設置 // 項目路徑 /home/www/ File pathFile = new File("/home/www/upload/"); if (!pathFile.exists()) { pathFile.mkdirs(); } //上傳文件地址 UUID uuid = UUID.randomUUID(); File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename()); files.transferTo(serverFile); String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/"); return imgPath; }
WangEditor富文本編輯器內容的顯示
-
HTML部分
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://unpkg.com/wangeditor/dist/wangEditor.min.js"></script>
<!-- ${urDetailBlog.getBlogContent()} 后台獲取的WangEditor編輯器提交的html代碼 --> <div id="detailBlog1" hidden th:text="${urDetailBlog.getBlogContent()}"></div> <div id="detailBlog"></div>
-
JavaScript部分
<script> $(function() { $("#detailBlog").html($("#detailBlog1").text()); }); </script>