使用WangEditor编辑器使用图片上传功能

发布时间 2024-01-05 10:41:09作者: 千樊

使用WangEditor编辑器上传图片的一些注意事项

首先就是前端的HTML与JS(2021-07-15 20:46:22)
WangEditor的优点是不用引入CSS文件只需要引入一个js文件-wangEditor.js
HTML
只需要一个DIV块即可

<div class="Comm-User-Write" id="userwrite"></div>

JS

<script type="text/javascript">
    var E = window.wangEditor
    var editor = new E('#userwrite')
    // 自定义菜单配置
    editor.config.menus = [//配置自己需要的菜单栏
        'emoticon',  // 表情
        'image',  // 插入图片
        'undo',  // 撤销
        'redo'  // 重复
    ]
    editor.config.uploadImgServer = '../Backstage/Image/CommUploadimage.php'//配置图片上传后台处理路径
    editor.config.uploadImgTimeout = 5 * 10000
    editor.create()
</script>

后台图像处理文件
参考隔壁好朋友
https://blog.csdn.net/qq_41614928/article/details/100541445

<?php
//empty():检查一个变量是否为空  /  $_FILES数组:接收上传的文件
if(!empty($_FILES)){ //提交的文件是否为空

  //把文件上传到../../Image/Community/目录  注意最后Community后面的/必须加
  $up_root = '../../Image/Community/';
  
  //该目录是否存在  || 不存在创建该目录
  is_dir($up_root) || mkdir($up_root);
  
  //遍历上传的文件
  foreach($_FILES as $item){
  
    //error = 0 表示文件正常可以上传
    if($item['error'] === 0){
        //读取文件信息
        $content = file_get_contents($item['tmp_name'],'r');
        
        //获取当前时间戳来构成上传文件的新名称
        $fid =  time();
        
        //文件名和后缀以'.'分开 得到一个$suffix数组
        $suffix = explode('.',$item['name']);
        
        //删除数组最后一位并返回 获得后缀名
        $suffix = array_pop($suffix);
        $suffix && ($suffix = '.'.$suffix);

        //move_uploaded_file 将上传的文件移动到新位置
        move_uploaded_file($item['tmp_name'],$up_root.$fid.$suffix);

        $link = 'http://demo.com/Image/Community/'.$fid.$suffix;//这里是构成了图片的连接形式
        
        //接下来是构造WangEditor编辑器的返回值
        //数据结构要求比较严格 当我配置好之后 上传图片能正常上传但是无法回显到编辑器的输入框最后发现$data外面必须要有[]这个符号
        $data1 = array(
                    "url"=>$link,
                    "alt"=>"",
                    "href"=>""
                );
        $data = array(
                    "errno"=> 0,
                    "data"=>[$data1]
                );

        $json = json_encode($data);//序列化数组
        exit($json);
        
    }else{
      $data1 = array(
                    "url"=>"",
                    "alt"=>"",
                    "href"=>""
                );
        $data = array(
                    "errno"=> 1,
                    "data"=>[$data1]
                );

        $json = json_encode($data);//序列化数组
        exit($json);
    };
  };
};