wangeditor在TP6中使用

6 阅读2分钟
  1. 加载编辑器基本配置
  2. 配置服务器页面地址
  3. 配置TP6路由
  4. 编写上传文件逻辑
  5. 新建上传文件夹(linux下要开启可写权限)
  6. 编写页面表单
  7. 测试

编辑器加载代码(可独立成一个文件随时装填):

/*1.编辑器声明*/
var html_content;
var { createEditor, createToolbar } = window.wangEditor;
var editorConfig = {
  placeholder: 'Type here...',
  onChange(editor) {
    html_content = editor.getHtml()
    //console.log('editor content', html_content)
    // 也可以同步到 <textarea>
  },
  MENU_CONF: {}//这里很重要,需要给editorConfig添加一个项目
}


/*2.上传图片*/
editorConfig.MENU_CONF['uploadImage'] = {
  //服务器页面地址
  server: 'upload_img',
  //文件名 ,默认值 'wangeditor-uploaded-image'
  fieldName: 'custom-field-name',
  // 单个文件的最大体积限制,默认为 2M
  maxFileSize: 1 * 1024 * 1024, // 1M
  // 最多可上传几个文件,默认为 100
  maxNumberOfFiles: 10,
  // 选择文件时的类型限制,默认为 ['image/*'] 。如不想限制,则设置为 []
  allowedFileTypes: ['image/*'],
  // 自定义上传参数,例如传递验证的 token 等。参数会被添加到 formData 中,一起上传到服务端。
  meta: {
    token: 'xxx',
    otherKey: 'yyy'
  },
  // 将 meta 拼接到 url 参数中,默认 false
  metaWithUrl: false,
  // 自定义增加 http  header
  headers: {
    Accept: 'text/x-json',
    otherKey: 'xxx'
  },
  // 跨域是否传递 cookie ,默认为 false
  withCredentials: true,
  // 超时时间,默认为 10 秒
  timeout: 5 * 1000, // 5 秒
  //上传图片之前
  onBeforeUpload(file) {
    //console.log(file);
    return 1;
  },
  // 单个文件上传失败
  onFailed(file, res) {
    console.log(`${file.name} 上传失败`);
    console.log(res)
  },
  // 单个文件上传成功之后
  onSuccess(file, res) {
    console.log(`${file.name} 上传成功`, res)

  }


}


/*3.编辑器实例化*/
var editor = createEditor({
  selector: '#editor-container',
  html: '<p><br></p>',
  config: editorConfig,
  mode: 'default', // or 'simple'
})
var toolbarConfig = {}
var toolbar = createToolbar({
  editor,
  selector: '#toolbar-container',
  config: toolbarConfig,
  mode: 'default', // or 'simple'
})

tp6后台代码:

public function upload_img()
    {

        $file_tmp = $_FILES['custom-field-name']['tmp_name'];
        $file_name = $_FILES['custom-field-name']['name'];
        $date = date("YmdHis");
        //获取文件扩展名
        $ext = pathinfo($file_name, PATHINFO_EXTENSION);
        //设置随机数
        $rand = rand(1000, 9999);
        $dir = 'upload2/' . $date . $rand . '.' . $ext;
        $dir2 = '/upload2/' . $date . $rand . '.' . $ext;

        move_uploaded_file($file_tmp, $dir);

        $success =
            [
                "errno" => 0,
                "data" => [
                    "url" => $dir2,
                    "alt" => "yyy",
                    "href" => "zzz"
                ]
            ];

        $str = json_encode($success);
        echo $str;
    }

路由配置:

Route::rule('admin/upload_img', 'admin0115/upload_img');