ECSHOP+Ckeditor5图片上传【PHP】

ECSHOP+Ckeditor5图片上传【PHP】

版本

classic

原来的坑

ClassicEditor
    .create( document.querySelector( '#editor' ),{
		language: 'zh-cn',
		toolbar: ["heading", "blockQuote", "imageUpload", "undo", "redo"],
			ckfinder: {
		           uploadUrl: "test.php?act=upload"
		       }
		})
    .then( editor => {
		window.editor = editor;
            };
    })
    .catch( error => {
        console.error( error );
    });

 

已上传至服务器,返回[“uploaded”:true, “url”:“image-path…”]或[“uploaded”:1, “url”:“image-path…”]均无效。

解决方案

前端

自建适配器

ClassicEditor
    .create( document.querySelector( '#editor' ),{
		language: 'zh-cn',
		toolbar: ["heading", "blockQuote", "imageUpload", "undo", "redo"]
		})
    .then( editor => {
		window.editor = editor;
		//加载适配器
		editor.plugins.get('FileRepository').createUploadAdapter = (loader)=>{
                return new UploadAdapter(loader);
            };
    })
    .catch( error => {
        console.error( error );
    });

class UploadAdapter {
    constructor(loader) {
        this.loader = loader;
    }
    upload() {
        return new Promise((resolve, reject) => {
            const data = new FormData();
            data.append('upload', this.loader.file);
            data.append('allowSize', 2);
            $.ajax({
                url: 'test.php?act=upload',
                type: 'POST',
                data: data,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function (data) {
                    if (data.res) {
                        resolve({
                            default: data.url
                        });
                    } else {
                        reject(data.msg);
                    }

                }
            });
           
        });
    }
    abort() {
    }
}

 

服务端

if ($_REQUEST['act'] == 'upload')
{
	require_once(ROOT_PATH . 'includes/cls_image.php');
	$image = new cls_image();
	
    //$uploadFilename = $_FILES['upload']['name']; 
    $uploadFilesize = $_FILES['upload']['size'];
	//上传图片不大于2M
    if($uploadFilesize > 1024*2*1000){
		$arr = array(
			'res' => false,
			'msg' => 'Pictures larger than 2M'
		);
		$json = stripslashes(json_encode($arr)); //去除反斜杠
		echo $json;
		exit;
    }
    //上传图片
	$headimg_original = $image->upload_image($_FILES['upload'],'actimage');
	if($headimg_original){
		$arr = array(
			'res' => true,
			'url' => $headimg_original
		);
	}else{
		$arr = array(
			'res' => false,
			'msg' => 'Image upload failure'
		);
	}
	$json = stripslashes(json_encode($arr)); //去除反斜杠
	//error_log($json, 3, "errors.log");
	echo $json;
}