ckedit4是没有图片上传功能的,单我们可以通过配置 config.js 文件来设置图片上传的接口,然后结合后端程序实现图片上传。本文讲解CKEditor4结合php实现上传图片功能的方法。
配置 config.js 文件
找到ckeditor
目录下的config.js
文件,添加两个配置
config.extraPlugins = 'uploadimage' config.filebrowserImageUploadUrl = '/api/UploadImg/upload.php' //filebrowserImageUploadUrl 替换成你需要上传的接口
我们点击图片按钮时候,便发现弹窗中多了上传的tag
界面 ,里面有选择文件按钮,可以上传图片到服务器,也就是会把file文件发送到上面设置的filebrowserImageUploadUrl接口。
upload.php 后端处理文件
TIPS:
1、ckedit4需要返回的json文件处理后续操作,使用json_encode;
2、$_REQUEST["ckCsrfToken"]是ckedit4需要的;
3、做了文件格式验证和文件大小处理;
4、文件名uniqid唯一处理。
<?php $callback = $_REQUEST["ckCsrfToken"]; $list=array("uploaded"=>'0','callback'=>$callback); $upaddress = "/uploads/allimg/".strftime("%Y%m",time())."/"; echo upload(); function upload(){ global $list,$upaddress; $callback = $_REQUEST["ckCsrfToken"]; $extensions = array("jpg","bmp","gif","png"); $allowed_types = ['image/jpeg', 'image/png', 'image/gif']; $uploadFilename = $_FILES['upload']['name']; $uploadFilesize = $_FILES['upload']['size']; $uploadFiletype = $_FILES['upload']['type']; $extension = pathInfo($uploadFilename,PATHINFO_EXTENSION); if(is_uploaded_file($_FILES['upload']['tmp_name']) && $uploadFilesize < 1024*300 && in_array($uploadFiletype, $allowed_types) && in_array($extension,$extensions)){ $uploadPath = $_SERVER['DOCUMENT_ROOT'].$upaddress; if(!file_exists($uploadPath)) { mkdir($uploadPath,0777,true); } $uuid = str_replace('.','',uniqid("",TRUE)).".".$extension; $desname = $uploadPath.$uuid; $tag = move_uploaded_file($_FILES['upload']['tmp_name'],$desname); $list['uploaded']=1; $list['fileName']=$uuid; $list['url']=$upaddress.$uuid; return json_encode($list); }else{ $list['error']="文件类型不对或文件太大!"; return json_encode($list); } } ?>