WangEditor富文本编辑器图片上传踩坑之路

        最近由于业务需求,需要用到富文本编辑器,找寻了好久,起初想使用百度的ueditor,但在使用的过程中实在是遇到了太多的坑,于是另外锁定了一款富文本编辑器——wangEditor。这是一款轻量级的富文本编辑器,比起百度的ueditor,这款编辑器的界面更加简单,文档也很详细。对于需求不是很高的功能来说,这款编辑器实在是不二之选。

一、wangEditor的基本显示demo

这个部分非常简单,官网文档也写得非常详细,直接参考官网即可

附上文档地址:https://www.kancloud.cn/wangfupeng/wangeditor3/335769

       下载地址:https://github.com/wangfupeng1988/wangEditor/releases 

编辑器效果如下:

二、图片上传后台接口编写

后台用到的是springboot+mybatis+mysql,为了方便测试,图片上传后是直接放在本地服务器。

2.1、Service层代码


 
 
  1. public interface IImgUploadService {
  2. String imgUpload(String imgPath);
  3. }
  4. @Service( "iImgUploadService")
  5. public class ImgUploadServiceImpl implements IImgUploadService {
  6. @Autowired
  7. private ImageUploadMapper imageUploadMapper;
  8. private static Logger logger = LoggerFactory.getLogger( "ImgUploadServiceImpl.class");
  9. /**
  10. * 存储上传图片的路径
  11. * @param
  12. * @return
  13. */
  14. public String imgUpload(String imgPath){
  15. ImageUpload upload = new ImageUpload();
  16. upload.setImgpath(imgPath);
  17. // 一定要加非空判断,否则会报空指针异常
  18. if(upload.getImgpath() == null){
  19. return "图片地址为空";
  20. }
  21. // logger.error("向数据库中存储的路径为:" + upload.getImgpath());
  22. // logger.error("传递过来的imgPath参数为:" + imgPath);
  23. // logger.error(upload.toString());
  24. int rowCount = imageUploadMapper.insertImgPath(upload.getImgpath());
  25. logger.error(rowCount + "");
  26. if(rowCount > 0){
  27. return "图片地址存储成功";
  28. }
  29. return "图片地址存储失败";
  30. }
  31. }

2.2、Controller层代码


 
 
  1. public class TestController {
  2. private static final Logger logger = LoggerFactory.getLogger( "TestController.class");
  3. private final ResourceLoader resourceLoader;
  4. @Autowired
  5. private IImgUploadService iImgUploadService;
  6. @Value("${web.upload-path}")
  7. private String path;
  8. @Value("${server.port}")
  9. private String port;
  10. @Autowired
  11. public TestController(ResourceLoader resourceLoader) {
  12. this.resourceLoader = resourceLoader;
  13. }
  14. /**
  15. * @param file 要上传的文件
  16. * @return
  17. */
  18. @ResponseBody
  19. @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
  20. public Map<String, String> upload( @RequestParam("file") MultipartFile file, HttpServletRequest request) {
  21. Map<String,String> map=new HashMap<>();
  22. String filePath = request.getSession().getServletContext().getRealPath(path);
  23. //生成随机字符串,用于图片命名
  24. String uuid = UUID.randomUUID().toString().replaceAll( "-", "");
  25. // 获得文件类型
  26. String fileType = file.getContentType();
  27. // 获得文件后缀名称
  28. String imageName = fileType.substring(fileType.indexOf( "/") + 1);
  29. // 原名称
  30. // String fileName = file.getOriginalFilename();
  31. // 新名称
  32. String newFileName = uuid + "." + imageName;
  33. System. out.println(imageName);
  34. try {
  35. FileUtils.upload(file.getBytes(), filePath, newFileName);
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. // 拼接图片url
  40. String imgHost = "http://127.0.0.1:" + port;
  41. String imgUploadPath = path;
  42. String imgName = newFileName;
  43. String imgPath = imgHost + imgUploadPath + imgName;
  44. iImgUploadService.imgUpload(imgPath);
  45. map.put( "url",imgPath);
  46. return map;
  47. }
  48. /**
  49. * 跳转到文件上传页面
  50. *
  51. * @return
  52. */
  53. @RequestMapping("test")
  54. public String toUpload() {
  55. return "ttt";
  56. }

2.3、前端HTML代码


 
 
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8"/>
  5. <title>ueditor-demo </title>
  6. <script th:src="@{${#httpServletRequest.getContextPath()}+'/js/jquery-1.7.1.min.js'}"> </script>
  7. <script th:src="@{${#httpServletRequest.getContextPath()}+'/js/wangEditor.min.js'}"> </script>
  8. </head>
  9. <body>
  10. <h2>wangEditor </h2>
  11. <div id="editor">
  12. <p>欢迎使用 <b>wangEditor </b> 富文本编辑器 </p>
  13. </div>
  14. <!-- 注意, 只需要引用 JS,无需引用任何 CSS !!!-->
  15. <script type="text/javascript" src="/wangEditor.min.js"> </script>
  16. <script type="text/javascript">
  17. var E = window.wangEditor;
  18. var editor = new E( '#editor');
  19. //开启debug模式
  20. editor.customConfig.debug = true;
  21. // 关闭粘贴内容中的样式
  22. editor.customConfig.pasteFilterStyle = false
  23. // 忽略粘贴内容中的图片
  24. editor.customConfig.pasteIgnoreImg = true
  25. // 使用 base64 保存图片
  26. //editor.customConfig.uploadImgShowBase64 = true
  27. editor.customConfig.uploadFileName = "file";
  28. editor.customConfig.uploadImgServer = '/fileUpload';
  29. editor.customConfig.debug = true;
  30. //自定义上传图片事件
  31. editor.customConfig.uploadImgHooks = {
  32. before: function (xhr, editor, files) {
  33. },
  34. success: function (xhr, editor, result) {
  35. console.log( "上传成功");
  36. },
  37. fail: function (xhr, editor, result) {
  38. console.log( "上传失败,原因是" + result);
  39. },
  40. error: function (xhr, editor) {
  41. console.log( "上传出错");
  42. },
  43. timeout: function (xhr, editor) {
  44. console.log( "上传超时");
  45. },
  46. customInsert: function (insertImg, result, editor) {
  47. // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
  48. // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
  49. // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
  50. var url = result.url;
  51. insertImg(url)
  52. // result 必须是一个 JSON 格式字符串!!!否则报错
  53. }
  54. };
  55. // 或者 var editor = new E( document.getElementById('editor') )
  56. editor.create()
  57. </script>
  58. </body>
  59. </html>

2.4、效果展示

 

三、踩坑经历

做的是一个小demo所以代码很简单。下面是我要说的重点,我的踩坑经历。

3.1、上传图片的参数问题

如果后台自定义的上传文件的参数,如图

那么前端js中就得添一句:

editor.customConfig.uploadFileName = 'file'
 
 

用于指定参数名,否则前端会出现“400”的错误。

3.2、图片上传的接口配置

在这里我被官网的文档给坑了一把,也许是我自己没理解清楚吧,唉!文档中如下图所说配置

配置地址用的是

editor.config.uploadImgUrl = '/upload';
 
 

然而我用这个确怎么也无法成功,编辑器都无法创建,后来更改为


 
 
  1. // 配置服务器端地址
  2. editor.customConfig.uploadImgServer = '/upload'

成功创建编辑器。

3.3、后台数据返回与编辑器内部图片显示

       如果我们通过上面配置的接口成功将图片上传至服务器了,现需要在编辑器里将刚上传的图片显示在编辑器里面。那么后台需要返回图片的url,格式如http://localhost:8011/uploadfiles/5168898981064558.jpeg,在浏览器中输入该url,然后回车,要能得到刚才上传的图片

例如:

接着要想让此图片在编辑器里面显示,还需要在前端自定义插入图片的事件,因为编辑器是不会自动插入图片的,贴出该事件的代码:


 
 
  1. customInsert: function (insertImg, result, editor) {
  2. // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
  3. // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
  4. var url = result.url
  5. insertImg(url)
  6. }

注意:result 必须是一个 JSON 格式字符串!!!否则报错

 

最后贴出demo的完整代码地址:https://gitee.com/1697923044/springboot-wangEditor

1、项目默认将图片上传到本地路径,如果需要上传到服务器路径直接在项目中进行修改即可,不要忘了修改存储到数据库中的路径。

2、项目没有使用任何图片上传控件或插件,原生springBoot实现,简单易上手。

3、项目使用Maven进行构建,朋友们在导入项目时不要导错了。

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值