注:
????ng2-ckeditor的github地址:https://github.com/chymz/ng2-ckeditor#readme
????CKEditor的配置均參考官方API:https://ckeditor.com/docs/
?????文章中使用的ckeditor版本:4.5.11
1.在項(xiàng)目引入ng2-ckeditor依賴
- 在index.html引入ckeditor.js鏈接
注:引用外部的鏈接的好處是可以利用CDN加速并且可以減輕服務(wù)器的壓力等等,但是項(xiàng)目有可能會在局域網(wǎng)中訪問粘衬,因此這里我采用的方式把當(dāng)前的ckeditor.js資源下載到了本地隘谣。
-
在index.html引入本地目錄
assets/core/base/ckeditor/
下的ckeditor.js
資源<script src="assets/core/base/ckeditor/ckeditor.js"></script>
-
在項(xiàng)目跟目錄下執(zhí)行以下命令拼苍,進(jìn)行安裝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', }, }, });
注:以上配置都是根據(jù)官方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';
// 去掉圖片預(yù)覽的中文字
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參數(shù)主要是顯示上傳到服務(wù)器按鈕,如下圖:
3.編寫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直接返回結(jié)果
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返回格式坚冀,未測試該代碼是否正確執(zhí)行
// 成功:{"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);
// 新建文件輸出流并對它進(jìn)行緩沖
FileOutputStream output = new FileOutputStream(newFile);
BufferedOutputStream outBuff = new BufferedOutputStream(output);
// 緩沖數(shù)組
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此緩沖的輸出流
outBuff.flush();
// 關(guān)閉流
inBuff.close();
outBuff.close();
output.close();
input.close();
relatePath = relatePath.replaceAll("\\\\", "/");
return relatePath;
}
注:對于CKEditor的方式一定要按照下圖代碼中的那樣抄谐,對于這種返回方法個人感覺不是很好惊畏,但是找了很多文檔也未找對應(yīng)的修改方式。
最終效果圖