1、配置编辑器(article.component.html):
<ckeditor [editor]="contentEditor" [data]="contentData" [config]="ckConfig" … ></ckeditor>
2、引入组件类(article.component.ts):
import Editor from '@ckeditor/ckeditor5-build-classic';
import {EditorConfig} from "@ckeditor/ckeditor5-core";
//源码后附
import {MyUploadAdapterPlugin} from 'my-upload.adapter';
.
.
.
.
.
.
contentData = "";
contentEditor = Editor;
ckConfig: EditorConfig = {
… …
extraPlugins: [MyUploadAdapterPlugin]
}
ngOnInit(): void {
// 设置图片上传路径
sessionStorage.setItem("imgUploadUrl", "http://127.0.0.1/img/upload");
}
3、编写插件类(my-upload.adapter.ts)
class MyUploadAdapter {
private readonly loader: any;
private xhr: any;
constructor(loader: any) {
// The file loader instance to use during the upload.
this.loader = loader;
}
// Starts the upload process.
upload() {
return this.loader.file
.then((file: any) => new Promise((resolve, reject) => {
this._initRequest();
this._initListeners(resolve, reject, file);
this._sendRequest(file);
}));
}
// Aborts the upload process.
abort() {
if (this.xhr) {
this.xhr.abort();
}
}
// Initializes the XMLHttpRequest object using the URL passed to the constructor.
_initRequest() {
const url = sessionStorage.getItem("imgUploadUrl");
if (url == undefined || url == "") {
console.error("The img.uploadUrl is not initiated...");
return;
}
// Note that your request may look different. It is up to you and your editor
// integration to choose the right communication channel. This example uses
// a POST request with JSON as a data structure but your configuration
// could be different.
const xhr = this.xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'json';
}
// Initializes XMLHttpRequest listeners.
_initListeners(resolve: any, reject: any, file: any) {
const xhr = this.xhr;
const loader = this.loader;
const genericErrorText = `上传文件失败:${file.name} !`;
xhr.addEventListener('error', () => reject(genericErrorText));
xhr.addEventListener('abort', () => reject());
xhr.addEventListener('load', () => {
const response = xhr.response;
// This example assumes the XHR server's "response" object will come with
// an "error" which has its own "message" that can be passed to reject()
// in the upload promise.
//
// Your integration may handle upload errors in a different way so make sure
// it is done properly. The reject() function must be called when the upload fails.
if (!response || response.error) {
return reject(response && response.error ? response.error.message : genericErrorText);
}
// If the upload is successful, resolve the upload promise with an object containing
// at least the "default" URL, pointing to the image on the server.
// This URL will be used to display the image in the content. Learn more in the
// UploadAdapter#upload documentation.
resolve({
default: response.url
});
});
// Upload progress when it is supported. The file loader has the #uploadTotal and #uploaded
// properties which are used e.g. to display the upload progress bar in the editor
// user interface.
if (xhr.upload) {
xhr.upload.addEventListener('progress', (evt: any) => {
if (evt.lengthComputable) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
});
}
}
// Prepares the data and sends the request.
_sendRequest(file: any) {
// Prepare the form data.
const data = new FormData();
data.append('file', file);
// Important note: This is the right place to implement security mechanisms
// like authentication and CSRF protection. For instance, you can use
// XMLHttpRequest.setRequestHeader() to set the request headers containing
// the CSRF token generated earlier by your application.
// Send the request.
this.xhr.send(data);
}
}
export class MyUploadAdapterPlugin {
constructor(editor: any) {
editor.plugins.get('FileRepository').createUploadAdapter = (loader: any) => {
// Configure the URL to the upload script in your back-end here!
return new MyUploadAdapter(loader);
}
}
}
4、编写服务端图片上传程序(以Java为例):
备注:上传成功,返回JSON格式的图片路径即可:{"url": “http://127.0.0.1/img/xxxx/xxxx/xxx.jpg”}
package com.javawind.blog.servlet;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
/**
* 文件上传
*/
@MultipartConfig
@WebServlet("/img/upload")
public class ImgUploadServlet extends HttpServlet {
private static final String ROOT_FOLDER = "/img/";
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
LocalDate localDate = LocalDate.now();
String dateFolder = localDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));
//以年月日命名文件夹,不存在则自动创建
String folder = ROOT_FOLDER + dateFolder;
String uploadPath = request.getServletContext().getRealPath(folder);
File uploadFolder = new File(uploadPath);
if (!uploadFolder.exists()) {
uploadFolder.mkdirs();
}
Part part = request.getPart("file");
//获取上传的文件名称
String fileName = part.getSubmittedFileName().toLowerCase();
String fileType = StringUtils.substringAfterLast(fileName, ".");
//验证上传文件格式
String[] allowFileTypes = {"jpg", "png", "gif", "bmp"};
if (!Arrays.asList(allowFileTypes).contains(fileType)) {
PrintWriter out = response.getWriter();
out.println("The file is not allow to upload: " + fileName);
out.flush();
return;
}
//重命名文件(这里以时间戳命名为例)
fileName = System.currentTimeMillis() + "." + fileType;
part.write(uploadPath + "/" + fileName);
//计算完整的图片路径
String uri = request.getRequestURI();
String url = request.getRequestURL().toString();
String host = url.replace(uri, "");
String imgUrl = host + request.getContextPath() + folder + fileName;
System.out.println("上传文件名:" + fileName);
System.out.println("文件存放的路径:" + uploadPath);
System.out.println("文件访问的路径:" + imgUrl);
//返回响应给ckeditor
String result = "{\"url\":\"" + imgUrl + "\"}";
PrintWriter out = response.getWriter();
out.println(result);
out.flush();
}
}