Takeaway:

Recently, I have been doing backend development of Thinkphp. Before, I used the rich text editor of LayUI. The advantage of LayUI is that it is easy to use, but the disadvantage is also obvious, that is, the editor has few functions. Let’s learn how to use CKEditor

Ckeditor4 download address (CKEditor 4.16 is selected for this tutorial) :

Ckeditor.com/ckeditor-4/…

Ckeditor core file ckeditor.js

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
Copy the code

Insert HTML controls where the editor is used

<textarea  id="content" name="content" cols="30" rows="2"></textarea>
Copy the code

Replace the corresponding control with editor code

<script type="text/javascript">
var editor;
window.onload = function()
{
	editor = CKEDITOR.replace( 'content', {
            filebrowserImageUploadUrl : '{:url("@admin/article/uploadPic")}'.// Upload the image to the backend URL
            image_previewText : '  '/// Remove the text displayed in the image upload preview area
    });
};
</script>
Copy the code

4. Enable upload function (upload function is hidden, so it needs to be enabled)

 

In ckeditor/plugins/image/dialogs/image. The js file, search: id: “Upload”, hidden:! 0,! 0 to false

5, ThinkPHP backend upload file method

After 4.10, the official document requires that the image be returned in json format after the image is uploaded successfully, as shown in the following example:

Upload successful return:


{
    "uploaded": 1."fileName": "demo.jpg"."url": "/files/demo.jpg"
}

{
    "uploaded": 1."fileName": "test.jpg"."url": "/files/test.jpg"."error": {
        "message": "A file with the same name already exists. The uploaded file was renamed to \"test.jpg\"."}}Copy the code

Upload failed:

{
    "uploaded": 0."error": {
        "message": "The file is too big."}}Copy the code

The code for uploading pictures on the back end:

/ * * *@name=' upload image '*/
    public function uploadPic()
    {
		// Note: Ckeditor uses Ajax to upload images, not form submission, so can't use request()->file() to receive images, only $_FILES
		$name = $_FILES['upload'] ['name']; 
		$size = $_FILES['upload'] ['size'];
		if($size  > 1024*2*1000) {$arr= array(
				"uploaded"= >0."error"= >"The size of the uploaded image cannot exceed 2M"
			);
			exit(json_encode($arr));
		}
		$extension = pathInfo($name,PATHINFO_EXTENSION);
		$types = array("jpg"."bmp"."gif"."png"); 		
		if(in_array($extension.$types)) {// Use the date as the folder name, for example, public/uploads/20210327/
			$dateFolder = date("Ymd",time());
			$path = ROOT_PATH . 'public/uploads/'.$dateFolder.DS;
			if(! file_exists($path)){
				mkdir($path.0777.true);
			}		
			$img_name  = str_replace('. '.' ',uniqid("".TRUE)).".".$extension; // Image name
			$save_path = $path.$img_name; // Save path
			$img_path  = '/uploads/'.$dateFolder.DS.$img_name; // Image path
			move_uploaded_file($_FILES['upload'] ['tmp_name'].$save_path);   
			$arr= array(
				"uploaded"= >1."fileName"= >$img_name."url"= >$img_path
			 );
		}else{ 
			$arr= array(
				"uploaded"= >0."error"= >"Image format is not correct (only.jpg/.gif/.bmp/.png files can be uploaded)"
			 );		 
		} 
		return json_encode($arr);
    }
Copy the code

Ckeditor (ckeditor

<script type="text/javascript">
var editor;
$(function() {
	editor = CKEDITOR.replace('content');
})
editor.document.getBody().getText();// Get plain text
editor.document.getBody().getHtml();// Get the HTML text
</script>
Copy the code

Use color plugins

1, need to download three plug-ins (one is not necessary), download address:

Ckeditor.com/cke4/addon/…

Ckeditor.com/cke4/addon/…

Ckeditor.com/cke4/addon/…

2. Unpack the downloaded plugins into ckeditor\plugins

3. Load the plug-in

Method 1: In the ckeditor/config.js file, add the plug-in configuration as follows:

CKEDITOR.editorConfig = function( config ) { ... Omit the previous code // load the plug-in config.extraPlugins ='colorbutton,panelbutton,floatpanel';
}
Copy the code

Method 2: When initializing the Editor in JS, add the configuration of the plug-in

<script type="text/javascript">
var editor;
window.onload = function()
{
	editor = CKEDITOR.replace( 'content', {
            filebrowserImageUploadUrl : '{:url("@admin/article/uploadPic")}'.// Upload the image to the backend URL
            image_previewText : '  './// Remove the text displayed in the image upload preview area
			extraPlugins: 'colorbutton'.// Use color plugins
    });
};
</script>
Copy the code

8. Customize toolbar configuration

Set in the ckeditor/config.js file

CKEDITOR.editorConfig = function( config ) {
	// Toolbar Settings
	config.toolbar = 'MyToolbar';
	config.toolbar_Full = [
		{ name: 'document'.items : [ 'Source'.The '-'.'Save'.'NewPage'.'DocProps'.'Preview'.'Print'.The '-'.'Templates'] {},name: 'clipboard'.items : [ 'Cut'.'Copy'.'Paste'.'PasteText'.'PasteFromWord'.The '-'.'Undo'.'Redo'] {},name: 'editing'.items : [ 'Find'.'Replace'.The '-'.'SelectAll'.The '-'.'SpellChecker'.'Scayt'] {},name: 'forms'.items : [ 'Form'.'Checkbox'.'Radio'.'TextField'.'Textarea'.'Select'.'Button'.'ImageButton'.'HiddenField']},'/',
		{ name: 'basicstyles'.items : [ 'Bold'.'Italic'.'Underline'.'Strike'.'Subscript'.'Superscript'.The '-'.'RemoveFormat'] {},name: 'paragraph'.items : [ 'NumberedList'.'BulletedList'.The '-'.'Outdent'.'Indent'.The '-'.'Blockquote'.'CreateDiv'.The '-'.'JustifyLeft'.'JustifyCenter'.'JustifyRight'.'JustifyBlock'.The '-'.'BidiLtr'.'BidiRtl'] {},name: 'links'.items : [ 'Link'.'Unlink'.'Anchor'] {},name: 'insert'.items : [ 'Image'.'Flash'.'Table'.'HorizontalRule'.'Smiley'.'SpecialChar'.'PageBreak'.'Iframe']},'/',
		{ name: 'styles'.items : [ 'Styles'.'Format'.'Font'.'FontSize'] {},name: 'colors'.items : [ 'TextColor'.'BGColor'] {},name: 'tools'.items : [ 'Maximize'.'ShowBlocks'.The '-'.'About']}]; config.toolbar_Basic = [ ['Bold'.'Italic'.The '-'.'NumberedList'.'BulletedList'.The '-'.'Link'.'Unlink'.The '-'.'About']]./ / custom
	config.toolbar_MyToolbar =[
        // In bold italic, underline through line subscript word superscript word
        ['Bold'.'Italic'.'Underline'.'Strike'.'Subscript'.'Superscript'].// Number list entity list decreases indentation increases indentation
        ['NumberedList'.'BulletedList'.The '-'.'Outdent'.'Indent'].// Align left, center, right, and ends
        ['JustifyLeft'.'JustifyCenter'.'JustifyRight'.'JustifyBlock'].// Cancel the hyperlink anchor
        ['Link'.'Unlink'.'Anchor'].// Image Flash table horizontal line emoji special character page break
        ['Image'.'Flash'.'Table'.'HorizontalRule'.'Smiley'.'SpecialChar'.'PageBreak'].'/'.// Style format font Size
        ['Styles'.'Format'.'Font'.'FontSize'].// Text color Background color
        ['TextColor'.'BGColor'].// Display block source code in full screen
        ['Maximize'.'ShowBlocks'.The '-'.'Source']
    ],
	config.format_tags = 'p; h1; h2; h3; h4; h5; h6; pre';
	config.removeButtons = 'Underline,Subscript,Superscript';
	config.removeDialogTabs = 'image:advanced; link:advanced';
	// Load the plug-in
	config.extraPlugins = 'colorbutton,panelbutton,floatpanel'; 
};
Copy the code