主要是实现两个功能:图片上传和保存文章内容至服务端
仅为笔记,仅供参考
环境参数
- @angular/cli 7.3.2
- macOS 10.14.3
- nodejs v9.0.0
- 其他信息详见package.json
环境搭建
首先,使用angular脚手架初始化项目(需要先全局安装 @angular/cli)
npm install -g @angular/cli
ng new ckeditor-angular
其次,安装 Ckeditor5 相关依赖,进入项目根目录
npm install --save @ckeditor/ckeditor5-angular
npm install --save @ckeditor/ckeditor5-build-classic
npm install --save @ckeditor/ckeditor5-ui
前两个是必须的,第三个是为了编写保存功能插件而安装的
安装完毕后使用编辑器打开项目,我使用的是 Intellij IDEA
在 src/app/app.module.ts 中添加 CKEditorModule
,如下
为了演示方便,将 src/app/app.component.html
和 src/app/app.component.css
删除,html内容在 src/app/app.component.ts
中编写,第一版代码具体代码如下
// src/app/app.component.ts
import {
Component} from '@angular/core';
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
@Component({
selector: 'app-root',
template: `
<ckeditor [editor]="Editor" data="<p>Hello, world!</p>">
</ckeditor>
`
})
export class AppComponent {
public Editor = ClassicEditor;
}
输入 ng serve
查看效果
至此环境搭建完毕
对Ckeditor进行配置
完成两项配置:1,中文化;2,自己配置按钮的数量类型
中文化
顺着包路径 node_modules/@ckeditor/ckeditor5-build-classic/build/translations
一路找下去就会发现有一大堆地区语言的js文件,其中就有 zh-cn.js
,将其加入到ts文件中,同时添加配置对象config
,传入到 组件 ckeditor
中,app.component.ts修改如下
import {
Component} from '@angular/core';
import * as ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import '@ckeditor/ckeditor5-build-classic/build/translations/zh-cn.js';
@Component({
selector: 'app-root',
template: `
<ckeditor
[editor]="Editor"
data="<p>Hello, world!</p>"
[config]="config"
>
</ckeditor>
`
})
export class AppComponent {
public Editor = ClassicEditor;
// 配置语言
public config = {
language: 'zh-cn'
};
}
效果如下
配置按钮
这个也是在那个 config
对象中配置,就添加上传图片的按钮和加粗的按钮吧,中间再填个一个分隔符,配置如下
//....
export class AppComponent {
public Editor = ClassicEditor;
public config = {
// 配置语言
language: 'zh-cn',
toolbar: ['imageUpload', '|', 'bold']
};
}
效果如下
更多按钮请参考官网文档
添加上传图片的功能
搭建测试文件服务器
首先,先搭建一个简单的提供文件上传下载功能的nodejs服务器
这里就在根目录下新建文件夹 file-server,进入其中,安装express等依赖
# 在 file-server 文件夹中
npm init
npm install --save express
npm install --save express-fileupload
npm install --save body-parser
新建app.js文件,向其中填写基础代码;新建uploads文件夹,作为上传文件的文件夹
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
const path = require('path');
const PORT = 8000;
// 用于解析post请求
const bodyParser = require('body-parser')
app.