就在最近,公司让我写一个后台,其中用到了富文本编辑器。自从这个富文本的出现 我就慢慢的进入了一个坑,起初不知道用什么编辑器好,看了好多好多,最后选择了。这个 wangeditor3。个人认为这个富文本很干净,还很多功能。

选择了编辑器 我就慢慢的走进了坑的道理,一步一个坎。接下来就是看代码了。

这个是wangeditor,选择一个自己喜欢的版本。我用的是3的

https://github.com/wangfupeng1988/wangeditor/releases

定义一个富文本编辑器

然后富文本就出现了

然后就是图片上传代码 首先要在js中配置点东西。

<script>
    var e = window.wangeditor;
    var editor = new e(‘#elm1‘);
    editor.customconfig.uploadimgserver = "uploads.php"; // 上传图片到服务器
    editor.customconfig.uploadfilename = "file";   //文件名称 也就是你在后台接受的 参数值
    editor.customconfig.uploadimgheaders = {  //header头信息 
      ‘accept‘: ‘text/x-json‘
    }
    // 将图片大小限制为 3m
    editor.customconfig.uploadimgmaxsize = 3 * 1024 * 1024  //默认为5m
    editor.customconfig.uploadimgshowbase64 = false;  // 使用 base64 保存图片
    // editor.customconfig.customalert = function (info) { //自己设置alert错误信息
    //   // info 是需要提示的内容
    //   alert(‘自定义提示:‘ + ‘图片上传失败,请重新上传‘)
    // };
    editor.customconfig.debug = true; //是否开启debug 默认为false 建议开启 可以看到错误
    // editor.customconfig.debug = location.href.indexof(‘wangeditor_debug_mode=1‘) > 0; // 同上 二选一
    //图片在编辑器中回显
    editor.customconfig.uploadimghooks = { 
      error: function (xhr, editor) {
        alert("2:" + xhr + "请查看你的json格式是否正确,图片并没有上传");
        // 图片上传出错时触发 如果是这块报错 就说明文件没有上传上去,直接看自己的json信息。是否正确
        // xhr 是 xmlhttprequst 对象,editor 是编辑器对象
      },
      fail: function (xhr, editor, result) {
        // 如果在这出现的错误 就说明图片上传成功了 但是没有回显在编辑器中,我在这做的是在原有的json 中添加了
        // 一个url的key(参数)这个参数在 custominsert也用到
        // 
        alert("1:" + xhr + "请查看你的json格式是否正确,图片上传了,但是并没有回显");
      },
      success:function(xhr, editor, result){
        //成功 不需要alert 当然你可以使用console.log 查看自己的成功json情况 
        //console.log(result)
        // insertimg(‘https://ss0.bdstatic.com/5av1bjqh_q23odcf/static/superman/img/logo/bd_logo1_31bdc765.png‘)
      },
      custominsert: function (insertimg, result, editor) {
        //console.log(result);
        // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
        // insertimg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
        // 举例:假如上传图片成功后,服务器端返回的是 {url:‘....‘} 这种格式,即可这样插入图片:
        insertimg(result.url);
      }
    };
    editor.customconfig.showlinkimg = true; //是否开启网络图片,默认开启的。
    editor.create()
  </script>

这些是javascript的配置代码。

详细的php代码在我的git里面 有兴趣的可以下载一下~

https://github.com/wjmgg/wangeditor3uploadforphp.git

这样wangeditor3的图片上传就完成了。

以上就是本次介绍的全部知识点内容,感谢大家对www.887551.com的支持。