注:
ng2-ckeditor的github地址:https://github.com/chymz/ng2-ckeditor#readme
CKEditor的配置均参考官方API:https://ckeditor.com/docs/
文章中使用的ckeditor版本:4.5.11
1.在项目引入ng2-ckeditor依赖
- 在index.html引入ckeditor.js链接
注:引用外部的链接的好处是可以利用CDN加速并且可以减轻服务器的压力等等,但是项目有可能会在局域网中访问,因此这里我采用的方式把当前的ckeditor.js资源下载到了本地。
-
在index.html引入本地目录
assets/core/base/ckeditor/
下的ckeditor.js
资源<script src="assets/core/base/ckeditor/ckeditor.js"></script>
-
在项目跟目录下执行以下命令,进行安装ng2-ckeditor
npm install ng2-ckeditor
-
在SystemJS config配置中加入以下配置
System.config({ map: { 'ng2-ckeditor': 'npm:ng2-ckeditor', }, packages: { 'ng2-ckeditor': { main: 'lib/index.js', defaultExtension: 'js', }, }, });
注:以上配置都是根据官方github上的说明而来,更多配置信息请参考ng2-ckeditor(github)
2.在angular2的组件中使用ng2-ckeditor
- 在本地目录
assets/core/base/ckeditor/
下配置config.js
config.js
:
CKEDITOR.editorConfig = function (config) {
// 富文本的背景色
config.uiColor = '#F8F8F8';
config.language = 'zh-cn';
// 选择自定义工具集
config.toolbar = 'Basic';
// 去掉图片预览的中文字
config.image_previewText = ' ';
config.removeDialogTabs = 'image:advanced;image:Link';
// 自己的定义的工具集
config.toolbar_Basic = [
['Maximize', 'Source'],
['Undo', 'Redo', 'Cut', ' Copy', 'Paste', 'PasteText', 'PasteFromWord',],
['Link', 'Unlink', 'Anchor', 'Image', 'Table'],
['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript'],
['NumberedList', 'BulletedList', 'Outdent', 'Indent', 'Blockquote'],
['Styles', 'Format', 'Font', 'FontSize', 'TextColor', 'BGColor'],
['HorizontalRule', 'Smiley', 'SpecialChar', 'Checkbox']
];
// 全部的工具集
config.toolbar_Full = [
{
name: 'document',
items: ['Source', '-', 'Save', 'NewPage', 'DocProps', 'Preview', 'Print', '-', 'Templates']
},
{name: 'clipboard', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']},
{name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-', 'SpellChecker', 'Scayt']},
{
name: 'forms',
items: ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField']
},
'/',
{
name: 'basicstyles',
items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']
},
{
name: 'paragraph',
items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', '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', '-', 'About']}
];
};
- app.module.ts
import { CKEditorModule } from 'ng2-ckeditor';
@NgModule({
// ...
imports: [CKEditorModule],
// ...
})
export class AppModule {}
- app.component.html
<ckeditor [(ngModel)]="mVZZArticle.content" [config]="mVZZConfig" debounce="500"></ckeditor>
{{mVZZArticle.content}}
- app.component.ts
export class AppComponent extends AppBaseComponent implements OnInit {
public mVZZArticle;
public mVZZConfig;
constructor() {
super();
}
ngOnInit() {
this.mVZZArticle = {content: null};
this.mVZZConfig = {filebrowserImageUploadUrl: '/xxx/uploadImageAddress'};
}
}
注:在这里配置了filebrowserImageUploadUrl参数主要是显示上传到服务器按钮,如下图:
3.png3.编写JAVA后端接受ckeditor图片接口
- FileUploadController.java
@RequestMapping(value = "/uploadfileByCK", method = RequestMethod.POST)
@ApiOperation(value = "Ckeditor表单上传文件", notes = "")
public void handleFormUploadByCkEditor(StandardMultipartHttpServletRequest request, HttpServletResponse response) {
try {
String rp = "";
Map<String, MultipartFile> files = request.getFileMap();
String relWebPathPrefix = appConfig.getResource().getUploadPrefix();
relWebPathPrefix = relWebPathPrefix.replace("/**", "");
String relativPathPrefix = appConfig.getResource().getPath();
Iterator<String> iterator = request.getFileNames();
if (iterator.hasNext()) {
String name = iterator.next();
MultipartFile file = files.get(name);
String fn = file.getOriginalFilename();
rp = this.handleFile(file.getInputStream(), relativPathPrefix, fn);
}
// 返回绝对路径
String fullPath = appConfig.getResource().getHost() + relativPathPrefix + rp;
// 使用response直接返回结果
PrintWriter out = response.getWriter();
String fullContentType = "text/html;charset=UTF-8";
response.setContentType(fullContentType);
String callback = request.getParameter("CKEditorFuncNum");
out = response.getWriter();
out.println("<script type=\"text/javascript\">");
out.write("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + fullPath + "');");
out.println("</script>");
// 使用json返回格式,未测试该代码是否正确执行
// 成功:{"uploaded":1,"fileName":"文件名.文件格式","url":"上传成功后得资源路径url"}
// 失败: {"uploaded":0,"error":{"message":"资源上传错误得原因..."}}
} catch (Exception e) {
throw new BusinessException("文件上传异常:" + e.getCause().getMessage());
}
}
/**
*
* @param file
* @param relativPathPrefix 相对路径前缀
* @param fileName
* @return
* @throws IOException
*/
private String handleFile(InputStream input, String relativPathPrefix, String fileName) throws IOException {
String sp = File.separator;
String date = DateUtils.parseToString(new Date(), "yyyyMMdd");
String newFilePath = appConfig.getResource().getDir() + relativPathPrefix + sp + date + sp;
File uploadpath = new File(newFilePath);
if (!uploadpath.exists()) {
uploadpath.mkdirs();
}
// 重命名文件
int start = fileName.lastIndexOf(".");
String fileSuffix = fileName.substring(start);
fileName = UUID.randomUUID().toString() + fileSuffix;
String newFile = newFilePath + fileName;
String relatePath = sp + date + sp + fileName;
BufferedInputStream inBuff = new BufferedInputStream(input);
// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(newFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
// 关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
relatePath = relatePath.replaceAll("\\\\", "/");
return relatePath;
}
注:对于CKEditor的方式一定要按照下图代码中的那样,对于这种返回方法个人感觉不是很好,但是找了很多文档也未找对应的修改方式。
4.png最终效果图
5.png
网友评论