0


SpringBoot+Vue2整合WangEditor富文本

一.简介

1.wangEditor:是一款轻量级 web 富文本编辑器,配置方便,使用简单,开源免费,几行代码即可生成。集成了所有常见功能,无需二次开发。

2.富文本:不止包含文字,还包含图片、表情、字体、表格、超链接、音频等内容的文本编辑器

二.整合步骤

1.配置环境

2.Vue前端整合编辑器

3.后端解决跨域问题

4.配置好图片上传地址

注:富文本就是把资源全部转成html的格式,其中图片等大文件保存,WangEditor提供了两种方式—— 1.一种是直接转码成Base64的格式保存,优点是减少服务器访问次数,解码简单操作简单,但是缺点是会导致文本内容较多,存在数据库中会增加数据库压力,体验不是很好。2.另一种方法是将图片上传是云服务器,好处是分担服务器的负载,数据库只需保存图片等url地址,减小数据库等压力。我采用的是第二种方式,使用springboot模拟云服务器。

5.将编辑器的数据上传给后端并保存在数据库

6.回显

三.实际操作

1.环境配置

npm 安装

  1. npm i wangeditor --save
  1. import E from 'wangeditor'
  2. const editor = new E('#div1')
  3. // 或者 const editor = new E( document.getElementById('div1') )
  4. editor.create()

2.Vue前端整合编辑器

tempalet里面是样式(就这么短,一个div就没了)

script里面是向后端提交数据的操作

  1. <template>
  2. <div>
  3. <div id="editor" style="width: 100%;" ></div>
  4. <button type="button" @click="ShowContent" >内容</button>
  5. <button type="button" @click="UploaderByAxios">上传</button>
  6. </div>
  7. </template>
  8. <script>
  9. import E from "wangeditor"
  10. export default {
  11. data() {
  12. return {
  13. editor: '',
  14. msg : {
  15. msg:""
  16. }
  17. }
  18. },
  19. methods: {
  20. setWangEditor() {
  21. // 创建编辑器
  22. this.editor = new E('#editor')
  23. this.editor.config.height= 500
  24. // 配置 onchange 回调函数
  25. this.editor.config.onchange = function (newHtml) {
  26. console.log("change 之后最新的 html", newHtml);
  27. };
  28. // 配置触发 onchange 的时间频率,默认为 200ms
  29. this.editor.config.onchangeTimeout = 500; // 修改为 500ms
  30. // 插入网络图片的回调
  31. this.editor.config.linkImgCallback = function (src) {
  32. console.log('图片 src ', src)
  33. //console.log('图片文字说明',alt)
  34. //console.log('跳转链接',href)
  35. }
  36. // 自定义检查插入视频的回调
  37. this.editor.config.onlineVideoCallback = function (video) {
  38. // 自定义回调内容,内容成功插入后会执行该函数
  39. console.log('插入视频内容', video)
  40. }
  41. //关闭样式过滤
  42. this.editor.config.pasteFilterStyle = false
  43. // 配置 server 接口地址
  44. this.editor.config.uploadImgServer = 'http://localhost:8181/uploadImg'
  45. this.editor.config.withCredentials = true
  46. this.editor.config.uploadFileName = 'myFileName'
  47. this.editor.config.uploadImgMaxSize = 5 * 1024 * 1024 //最大上传5M的图片
  48. this.editor.config.uploadImgMaxLength = 1 // 一次最多上传 1 个图片
  49. this.editor.config.uploadImgHooks = {
  50. customInsert: function (insertImg, result, editor) {
  51. //console.log(result.data)
  52. var url = result.data.url;//获取后台返回的url
  53. insertImg(url);
  54. }
  55. };
  56. //this.editor.config.uploadImgShowBase64 = true
  57. // 配置alt选项
  58. this.editor.config.showLinkImgAlt = false
  59. // 配置图片超链接
  60. this.editor.config.showLinkImgHref = false
  61. this.editor.create()
  62. },
  63. ShowContent(){
  64. alert(this.editor.txt.html() )
  65. //alert(this.editor.txt.text())
  66. },
  67. UploaderByAxios(){
  68. const _this = this;
  69. this.msg.msg = this.editor.txt.html()
  70. alert(_this.msg.msg)
  71. axios.post('http://localhost:8181/uploadHtml',_this.msg ).then(function (resp){
  72. //console.log(resp.data)
  73. alert(resp.data);
  74. })
  75. // axios.get('http://localhost:8181/uploadImg?html'+ _this.msg.Html ).then(function (resp){
  76. // console.log(resp.data)
  77. // // _this.tableData = resp.data.tableData
  78. // // _this.total = resp.data.total
  79. // })
  80. }
  81. },
  82. // <!--created 在模板渲染成html前调用,即通常初始化某些属性值,然后再渲染成视图-->
  83. // <!--mounted在模板渲染成html后调用,通常是初始化页面完成后,再对html的dom节点进行一些需要的操作。-->
  84. mounted() {
  85. this.setWangEditor()
  86. }
  87. }
  88. </script>
  89. <style scoped>
  90. </style>

3.后端解决跨域问题

解决跨域问题

4.配置好图片上传地址

接收vue传来的图片保存在本地,并返回图片的url(下面两段代表里面的路径要改,改成图片存放的路径)

  1. //WangEditor上传图片
  2. @RequestMapping(value = "/uploadImg", method = RequestMethod.POST)
  3. @ResponseBody
  4. public Map<String, Object> uploadImg(@RequestParam(value="myFileName") MultipartFile file, HttpServletRequest request) {
  5. String separator = System.getProperty("file.separator");
  6. separator=separator.replaceAll("\\\\","/");
  7. String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath()+ separator; //获取项目路径+端口号 比如:http://localhost:8181/
  8. try {
  9. String filePath="";
  10. //获取源文件
  11. filePath="/Users/huangjw/Documents/imgUploads/" ;//存储地址,此处也可以在application.yml中配置对象用@Value("${*.**}")注解注入内容
  12. String filename = file.getOriginalFilename();//获取图片名
  13. String[] names=filename.split("\\.");//获取后缀格式
  14. String uploadFileName=UUID.randomUUID().toString()+"."+names[names.length-1];//生成新图片
  15. File targetFile = new File(filePath,uploadFileName);//目标文件
  16. if (!targetFile.getParentFile().exists()){
  17. targetFile.getParentFile().mkdirs();
  18. }
  19. //传图片一步到位
  20. file.transferTo(targetFile);
  21. Map<String, Object> map = new HashMap<String, Object>();
  22. Map<String, String> data = new HashMap<>();
  23. data.put("url",basePath+"imgUploads/"+uploadFileName);//这里应该是项目路径,返回前台url
  24. data.put("alt",null);
  25. data.put("href",null);
  26. map.put("errno",0);
  27. map.put("data",data);
  28. //System.out.println(map.get("data"));
  29. return map;
  30. } catch (Exception e) {
  31. // TODO Auto-generated catch block
  32. e.printStackTrace();
  33. return null;
  34. }
  35. }


​​​​​​​

配置文件,通过url访问本地的图片

  1. import org.springframework.context.annotation.Configuration;
  2. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  3. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  4. @Configuration
  5. public class MyWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
  6. @Override
  7. public void addResourceHandlers(ResourceHandlerRegistry registry){
  8. //指向外部目录
  9. registry.addResourceHandler("imgUploads/**").addResourceLocations("file:/Users/huangjw/Documents/imgUploads/");
  10. super.addResourceHandlers(registry);
  11. }
  12. }

5.将编辑器的数据上传给后端并保存在数据库

这个很简单,数据就是html,存在数据库就行

  1. //上传WangEditor数据
  2. @RequestMapping(value = "/uploadHtml", method = RequestMethod.POST)
  3. @ResponseBody
  4. public String uploadHtml(@RequestBody Msg msg){
  5. EditorTest e = new EditorTest();
  6. e.setContent( msg.getMsg().toString());
  7. e.setId(1);
  8. editorTestService.insertSelective(e);
  9. return "success";
  10. }

6.回显

这个也比较简单,vue请求,然后v-html绑定数据就行

  1. <template>
  2. <div>
  3. <h3>内容预览</h3>
  4. <!-- <textarea id="" v-html="editorData"></textarea>-->
  5. <div v-html="editorData"></div>
  6. <!-- cols="170" rows="20"-->
  7. <button type="button" @click="ShowEditor">内容显示</button>
  8. </div>
  9. </template>
  10. <script>
  11. //引用
  12. import E from "wangeditor";
  13. export default {
  14. data() {
  15. return {
  16. editorData: ""
  17. }
  18. },
  19. methods:{
  20. ShowEditor(){
  21. const _this = this;
  22. axios.get('http://localhost:8181/getHtml').then(function (resp){
  23. console.log(resp.data)
  24. _this.editorData = resp.data;
  25. // _this.tableData = resp.data.tableData
  26. // _this.total = resp.data.total
  27. })
  28. }
  29. },
  30. mounted() {
  31. //初始化
  32. }
  33. }
  34. </script>

接收请求,然后返回数据

  1. @RequestMapping(value = "getHtml",method = RequestMethod.GET)
  2. public Object getHtml(){
  3. EditorTest e = editorTestService.selectByPrimaryKey(1);
  4. return e.getContent();
  5. }

标签: vue.js 前端 编辑器

本文转载自: https://blog.csdn.net/I_am_a_caiji/article/details/125120162
版权归原作者 a卷心菜 所有, 如有侵权,请联系我们删除。

“SpringBoot+Vue2整合WangEditor富文本”的评论:

还没有评论