WangEditor 富文本编辑器是一款轻量、简洁、易用、开源免费的编辑器
WangEditor富文本编辑器的导入
<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富文本编辑器的使用
<div id="editor"></div>
<textarea style="display: none" name="blogContent" id="blogContent"></textarea>
<!-- 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>
// 上传文件
@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富文本编辑器内容的显示
<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>
<script>
$(function() {
$("#detailBlog").html($("#detailBlog1").text());
});
</script>