LayUI富文本域使用案例

您所在的位置:网站首页 越狱密室逃脱攻略大全下载 LayUI富文本域使用案例

LayUI富文本域使用案例

2023-11-18 01:43| 来源: 网络整理| 查看: 265

LayUI富文本域是一款轻量级的富文本编辑器,页面设计比较简约。之前写项目时因为用的是LayUI框架,所以富文本域当时就用的LayUI富文本编辑器,这里整理一下。

先来看一下效果图,页面效果图。

 

访问效果图:

首先需要引入LayUI的JS和CSS样式文件。

显示LayUI的富文本域页面只需要放一个textarea标签,可以设置富文本域的默认值。

之后用JS渲染页面。

layui.use(['layedit', 'form'], function(){ var form = layui.form; var layedit = layui.layedit; layedit.set({ //设置图片接口 uploadImage: { url: 'layEdit/upload', //接口url type: 'post' } }); //创建一个编辑器,lay_edit为textarea标签的id值 var index = layedit.build('lay_edit',{ height: 350 //设置编辑器的高度 }); //提交时把值同步到文本域中 form.verify({ //content富文本域中的lay-verify值 content: function(value) { return layedit.sync(index); } }); });

上面代码主要有三部分。

设置图片上传的接口。

layedit.set({ //设置图片接口 uploadImage: { url: 'layEdit/upload', //接口url type: 'post' } });

图片上传后台方法。

@RequestMapping(value="/upload") @ResponseBody public Object upload(MultipartFile file) { String filename = file.getOriginalFilename(); String uuid = UUID.randomUUID().toString(); boolean boole = fileService.saveFile(file, uuid); if (boole) { Map map = new HashMap(); Map map2 = new HashMap(); map.put("code", 0); //0表示上传成功 map.put("msg","上传成功"); //提示消息 map2.put("src", "http://localhost/layEdit/download?uuid="+uuid); map2.put("title", filename); map.put("data", map2); return map; } else { return file.getOriginalFilename(); } }

返回的数据格式是LayUI固定的,LayUI前台接收返回的数据格式为:

{       "code": 0,      //0表示成功,其他表示失败       "msg": "",       //提示信息,//一般上传失败后返回       "data":  {            "src": "图片路径",            "title":  "图片名称"    //可选       } }

其中saveFile方法为图片上传方法,上传返回的地址是下载方法的地址,其代码如下。

// 图片存放位置 private final static String IMAGEPATH="e:\\layui\\image"; //保存图片 @Transactional public boolean saveFile(MultipartFile file, String uuid){ try{ File path = path(file.getContentType()); String filename = file.getOriginalFilename(); FileImg fileEntity = new FileImg(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date=new Date(); fileEntity.setFileName(filename); fileEntity.setUuid(uuid); String storeaddress = path.getAbsolutePath(); fileEntity.setStoreaddress(storeaddress); File saveFile = new File(path,uuid); try { fileRepository.save(fileEntity); file.transferTo(saveFile); return true; } catch (IllegalStateException | IOException e) { e.printStackTrace(); return false; } }catch (Exception e){ System.out.println("图片保存异常"); return false; } } //图片地址是否存在 private File path(String filename) { File pat=new File("e:\\layui"); File path = new File(FileService.IMAGEPATH); if(!pat.isDirectory()) { pat.mkdir(); } if(!path.isDirectory()) { path.mkdir(); } return path; } /** * 下载 * @param uuid * @param request * @param response */ public void download(String uuid, HttpServletRequest request, HttpServletResponse response) { FileImg fileentity = fileRepository.findByUuid(uuid); String filename = fileentity.getFileName(); filename = getStr(request, filename); File file = new File(fileentity.getStoreaddress(), uuid); if(file.exists()) { FileInputStream fis; try { fis = new FileInputStream(file); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment; filename=" + filename ); ServletOutputStream out = response.getOutputStream(); byte[] buf=new byte[2048]; int n=0; while((n=fis.read(buf))!=-1){ out.write(buf, 0, n); } fis.close(); out.flush(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } private String getStr(HttpServletRequest request, String fileName) { String downloadFileName = null; String agent = request.getHeader("USER-AGENT"); try { if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){ //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?="; //设置字符集 downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(fileName.getBytes("UTF-8")) + "?="; }else{ downloadFileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return downloadFileName; }

渲染textarea富文本域。

//创建一个编辑器,lay_edit为textarea标签的id值 var index = layedit.build('lay_edit',{ height: 350 });

其他属性参数。

属性类型描述toolArray重新定制编辑器工具栏,如: tool: ['link', 'unlink', 'face']hideToolArray不显示编辑器工具栏,一般用于隐藏默认配置的工具barheightNumber设定编辑器的初始高度uploadImageObject设定图片上传接口,如:uploadImage: {url: '/upload/', type: 'post'}

目前LayUI富文本域可选的Bar有(顺序可以自由排列):

tool: [ 'strong' //加粗 ,'italic' //斜体 ,'underline' //下划线 ,'del' //删除线 ,'|' //分割线 ,'left' //左对齐 ,'center' //居中对齐 ,'right' //右对齐 ,'link' //超链接 ,'unlink' //清除链接 ,'face' //表情 ,'image' //插入图片 ,'help' //帮助 ]

同步富文本域中的数据。

//提交时把值同步到textarea文本域中 form.verify({ //content富文本域中的lay-verify值 content: function(value) { return layedit.sync(index); } });

通过上面的JS渲染代码就可以得到一个完整的富文本域了,效果图如下(可以根据自己需求修改属性)。

页面全部代码。

#myForm{ background: white; padding: 30px; } 标题 发布人 内容 保存 layui.use(['layedit', 'form'], function(){ var form = layui.form; var layedit = layui.layedit; layedit.set({ //设置图片接口 uploadImage: { url: 'layEdit/upload', //接口url type: 'post' } }); //创建一个编辑器 var index = layedit.build('lay_edit',{ height: 350 }); //提交时把值同步到文本域中 form.verify({ //content富文本域中的lay-verify值 content: function(value) { return layedit.sync(index); } }); form.on("submit(formSubmit)", function (data) { console.log(data.field); $.post("layEdit/save", data.field, function(result){ layer.msg(result.msg,{offset:'rb'}); }); return false; }) });

关于富文本域的部分上面已经说的很清楚了,JS部分还包含了一个保存的方法。因为在富文本域渲染时设置了,提交时把值同步到textarea文本域中。所以这里就不用管了。

保存时,我们可以通过控制台输出看到表单序列化后的参数。

后台保存方法,新增和修改保存公用的一个方法,用ID作为区分,ID为null是新增,不为null为修改。

@Override public Object save(LayEditForm form) throws InstantiationException, IllegalAccessException { try { LayEdit model = new LayEdit(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Integer id = form.getId(); if(id!=null) { model=layEditService.findById(id); }else{ form.setCreatdate(sdf.format(new Date())); } BeanUtils.copyProperties(form, model,"id"); layEditService.save(model); return new AjaxResult("数据保存成功"); } catch (Exception e) { return new AjaxResult(false,"数据保存失败"); } }

就写到这里了,如果还什么问题欢迎下方留言交流。

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3