layui富文本编辑器
这篇文章介绍一下富文本编辑器,包括代码和实现
·
这篇文章介绍一下富文本编辑器,包括代码和实现
1.首先介入一个富文本的Demo,先看一下代码
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>ueditor demo</title>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"
></script>
<script src="esdk-obs-browserjs.3.22.3.min.js"></script>
</head>
<body>
<!-- 加载编辑器的容器 -->
<div id="div1">
<p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>
</div>
<!-- 引入 wangEditor.min.js -->
<script type="text/javascript">
const E = window.wangEditor
const editor = new E('#div1')
// 或者 const editor = new E( document.getElementById('div1') )
editor.config.menuTooltipPosition = 'down'
editor.config.showLinkImg = false
editor.config.debug = true;
// 关闭粘贴内容中的样式
editor.config.pasteFilterStyle = false
// 忽略粘贴内容中的图片
editor.config.pasteIgnoreImg = true
// 使用 base64 保存图片
//editor.customConfig.uploadImgShowBase64 = true
// 上传图片到服务器
editor.config.uploadFileName = 'myFile'; //设置文件上传的参数名称
editor.config.uploadImgServer = 'upload.do'; //设置上传文件的服务器路径
editor.config.uploadImgMaxSize = 3 * 1024 * 1024; // 将图片大小限制为 3M
editor.config.customUploadImg = (resultFiles, insertImgFn)=>{
// resultFiles 是 input 中选中的文件列表
// insertImgFn 是获取图片 url 后,插入到编辑器的方法
var bb=resultFiles[0];
//alert(JSON.stringify(bb));
//alert(JSON.stringify(insertImgFn));
// 上传图片,返回结果,将图片插入到编辑器中
// var objname= "deploy/ringpai/upload/dcm/" + 123456789 + ".png";
// obsClient.putObject({
// Bucket : 'ringpai-phis',
// Key : 'objname',
// SourceFile : document.getElementById('input-file').files[0]
//}, function (err, result) {
// if(err){
// console.error('Error-->' + err);
// }else{
// alert(JSON.stringify(result));
// console.log('Status-->' + result.CommonMsg.Status);
// }
//});
//insertImgFn(imgUrl)
}
editor.config.uploadImgHooks = {
before: function(xhr, editor, files) {
alert(JSON.stringify(files));
},
success: function(xhr, editor, result) {
console.log("上传成功");
},
fail: function(xhr, editor, result) {
console.log("上传失败,原因是" + result);
},
error: function(xhr, editor) {
console.log("上传出错");
},
timeout: function(xhr, editor) {
console.log("上传超时");
}
}
editor.create()
var obsClient = new ObsClient({
access_key_id: 'OHECMDFOILGX92Z3XDQC',
secret_access_key: 'OtxQhPAocSx0ZizvXCCMXlWVQ1GVJq2ByPsjBDNd',
server : 'obs.cn-north-4.myhuaweicloud.com'
});
// alert(obsClient);
</script>
</body>
</html>
这里需要引入一个js包,代码中也有体现,样式大概是下面这种
2.实际的应用(包含接口的编写)
以下的代码只能参考,不能完全粘贴复用,我这里的富文本是一个弹出的界面,只列出富文本的代码,主页面没有列出;可以看代码注释,上传图片视频的接口也会列出,存储文本,回显等接口就不列出了图片和视频的存储是通过华为云进行的,先存到华为云,然后把url存储到数据库中,实现回显
<div class="layui-form"
lay-filter="LAY-notificationMessage-SysMessagepupop-table">
<script type="text/html" id="LAY-notificationMessage-SysMessagepupop-tpl">
<div class="layui-form-item" style="margin-left: 430px;">
<div class="layui-inline">
<label class="layui-form-label" style="width: 150px;">标题</label>
<div class="layui-input-inline">
{{# if (d.state == "0" || d.state=='') { }}
<input type="text" name="title" placeholder="请输入" autocomplete="off"
value="{{d.title}}" class="layui-input search-class">
{{# } else if (d.state === "1") { }}
<input type="text" name="title" placeholder="请输入" autocomplete="off"
value="{{d.title}}" readonly class="layui-input search-class">
{{# } else if (d.state === "2") { }}
<input type="text" name="title" placeholder="请输入" autocomplete="off"
value="{{d.title}}" readonly class="layui-input search-class">
{{# } }}
</div>
</div>
</div>
<div style="margin-top:10px">
<label class="layui-form-label" style="padding-left: 0px;">发布内容:</label>
<div class="layui-form-item" id="textArea">
</div>
<div class="layui-form-item">
{{# if (d.state == "0" || d.state =='' || d.state === "2") { }}
<div class="layui-input-inline" style="float: right; width: 260px;">
<input type="submit" lay-submit lay-filter="LAY-notificationMessage-SysMessagepupop-releaseAndSave"
id="LAY-notificationMessage-SysMessagepupop-releaseAndSave" value="保存&发布" class="layui-btn">
<input type="button" lay-submit lay-filter="LAY-notificationMessage-SysMessagepupop-release"
value="保存"
class="layui-btn">
<input type="button" lay-submit lay-filter="LAY-notificationMessage-SysMessagepupop-cancelbtn"
value="取消"
class="layui-btn layui-btn-primary">
</div>
{{# } else if (d.state === "1") { }}
<div class="layui-input-inline" style="float: right;width: 60px;">
<input type="button" lay-submit lay-filter="LAY-notificationMessage-SysMessagepupop-cancelbtn"
value="关闭"
class="layui-btn layui-btn-primary">
</div>
{{# } }}
</div>
</div>
</script>
<div id="LAY-notificationMessage-SysMessagepupop-popupRevisitCancelView"></div>
</div>
<script type="text/template" template>
{{# layui.data.done(d); }}
</script>
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/wangeditor@latest/dist/wangEditor.min.js"
></script>
<script>
layui.data.done = function (d) {
layui.use(['admin', 'view', 'table', 'form', 'layer', 'laydate'], function () {
var admin = layui.admin,
layer = layui.layer,
view = layui.view,
laytpl = layui.laytpl,
$ = layui.$,
form = layui.form;
var organizeId = sessionStorage.getItem('organizeId');
var localData = layui.data(layui.setter.tableName);
const callback = d.params.callback || function () {
};
var detailsflage = d.params.detailsflage
console.log(d, 'd得内容')
var index = d.params.index;
var data = {
"state": d.params.data.state ? d.params.data.state : '',
"title": d.params.data.title ? d.params.data.title : '',
"content": d.params.data.content ? d.params.data.content : '',
}
var view = document.getElementById("LAY-notificationMessage-SysMessagepupop-popupRevisitCancelView");
var tmpl = document.getElementById('LAY-notificationMessage-SysMessagepupop-tpl').innerHTML;
laytpl(tmpl).render(data, function (html) {
view.innerHTML = html;
});
// ————————————富文本编辑器开始————————
setTimeout(function () {
const E = window.wangEditor;
const editor = new E('#textArea');
//重新加载当前页面
// location.reload();
// editor.config.text = d.params.data.content;
var value = '';
var id = d.params.data.id;
// editor.setContent(value);
// 或者 const editor = new E( document.getElementById('textArea') )
// editor.config.insertText(value)
editor.config.menuTooltipPosition = 'down'
editor.config.showLinkImg = false
editor.config.debug = true;
// 关闭粘贴内容中的样式
editor.config.pasteFilterStyle = false
// 忽略粘贴内容中的图片
editor.config.pasteIgnoreImg = true
// 使用 base64 保存图片
// editor.config.uploadImgShowBase64 = true
// 上传图片到服务器
editor.config.uploadFileName = 'file'; //设置文件上传的参数名称
// editor.config.uploadImgServer = ; //设置上传文件的服务器路径
// editor.config.uploadImgMaxSize = 3 * 1024 * 1024; // 将图片大小限制为 3M
//上传图片
editor.config.customUploadImg = function (files, insert) {
// files 是 input 中选中的文件列表
// insert 是获取图片 url 后,插入到编辑器的方法
for (let i = 0; i < files.length; i++) {
var form = new FormData();
form.append("file", files[0]);
$.ajax({
url: ,
type: "post",
processData: false,
contentType: false,
data: form,
dataType: 'json',
success(res) {
// 上传代码返回结果之后,将图片插入到编辑器中
console.log("上传成功");
console.log(res);
insert(res.data);
}
})
}
};
//上传视频
editor.config.customUploadVideo = function (files, obj) {
var form = new FormData();
form.append("file", files[0]);
$.ajax({
url:
type: "POST",
data: form,
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
console.log("上传成功");
console.log(result);
obj(result.data);
}
});
};
console.log('shang')
editor.config.onchange = function (html) {
// 监控变化,同步更新到 textarea
console.log($('#content'), 'sdlfjsldkjfslkdflk')
$('#content').val(html)
};
$.ajax({
url:
type: "POST",
data: form,
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
success: function (result) {
value = result.data;
}
});
//创建富文本编辑器
editor.create()
editor.txt.html(value);
//初始化时将变量值插入到编辑器文字域中
if (d.params.data.state === "1") {
if (d.params.data.content === '') {
// 禁用
editor.disable();
} else if (d.params.data.content != '') {
// 禁用
editor.disable();
}
}
//点击了保存并发布
form.on('submit(LAY-notificationMessage-SysMessagepupop-releaseAndSave)', function (data) {
//抓取富文本编辑器内容赋值到对应变量中
var content = editor.txt.html();
var field = data.field;
var state = 1;
var flage = 2;
field.content = content;
field.state = state;
field.id = d.params.data.id;
console.log(field)
checkMath(field, flage);
})
//点击了保存
form.on('submit(LAY-notificationMessage-SysMessagepupop-release)', function (data) {
var content = editor.txt.html();
var field = data.field;
console.log(d.params.data.state)
// debugger
field.content = content;
field.state = "0";
var flage = 1;
field.id = d.params.data.id;
console.log(field)
checkMath(field, flage)
})
}, 500)
// ————————————富文本编辑器结束————————
// 启用
// editor.enable();
//点击了取消
form.on('submit(LAY-notificationMessage-SysMessagepupop-cancelbtn)', function (data) {
layer.close(index);
})
function checkMath(field, flage) {
if (field.title === '' || field.title == undefined) {
return layer.msg('消息通知标题不能为空,请添加消息标题');
}
if (field.content === '' || field.content == undefined) {
return layer.msg('消息内容不能为空,请输入消息内容');
}
var loading = layer.msg('处理中', {
icon: 16,
shade: 0.01,
time: 0
});
$.ajax({
url: ,
data: JSON.stringify({
data: {
id: d.params.data.id,
version: d.params.data.version,
state: field.state,
content: field.content,
title: field.title
},
}),
type: 'post',
contentType: 'application/json; charset=utf-8',
success: function (res) {
if (res.code == 0) {
layer.msg("操作成功");
layer.close(loading);
layer.close(index);
callback();
}
},
error: function (resp) {
layer.close(loading);
layer.msg('系统错误,请联系管理员。', {
icon: 5
});
}
});
}
})
}
</script>
<style>
.LAY-custservice-visit-clickMe {
color: #077aff;
padding: 0 5px;
text-decoration: revert;
cursor: pointer;
}
.w-e-text-container {
height: 420px !important; /*!important是重点,因为原div是行内样式设置的高度300px*/
}
</style>
以下是存储到华为云的基本代码,只列出基本的代码,仅供参考
@Override
public String yunUploadFile(MultipartFile file) throws Exception {
String ak = "";
String sk = "";
String endPoint = "";
String bucketName = "";
//设置链接失效时间
// long expireSeconds = 3600 * 24 * 365L;
// 得到文件原名
String fileName = "sysnotifacation/" + file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
//创建云服务器
ObsClient obsClient = new ObsClient(ak, sk, endPoint);
PutObjectResult putObjectResult = obsClient.putObject(bucketName, fileName, inputStream);
int statusCode = putObjectResult.getStatusCode();
String obsurl = putObjectResult.getObjectUrl();
logger.info("-------OBS上传状态为:" + statusCode);
logger.info("-------文件的全路径为:" + obsurl);
inputStream.close();
// // 创建ObsClient实例
// TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
// request.setBucketName(bucketName);
// request.setObjectKey(file.getOriginalFilename());
//
// // 设置图片处理参数,对图片依次进行缩放、旋转
// Map<String, Object> queryParams = new HashMap<String, Object>();
// queryParams.put("x-image-process", "image/resize,m_fixed,w_100,h_100/rotate,90");
// request.setQueryParams(queryParams);
//
// // 生成临时授权URL
// TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
// System.out.println(response.getSignedUrl());
obsClient.close();
// return response.getSignedUrl();
return obsurl;
}
定义的参数根据自己华为云的参数来写就行,其他的数据接口不展示
以上的代码仅供参考,不能复用,有问题可以私信一起研究哈
更多推荐
已为社区贡献2条内容
所有评论(0)