本文适用于使用CKEditor5的官方默认向导生成的CKEditor5,但也可能对其他方式的有同样的意义。
对于上传图片这一块,这个默认的带上了ckfinder作为前端的上传插件。
假设我们的上传api,url是:/api/upload
那么,客户端只要这么配置:
var uploadApi = document.location.origin + "/api/upload"; ClassicEditor.create( document.querySelector( '#article-editor' ), { toolbar: { items: [ 'heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', '|', 'indent', 'outdent', '|', 'imageUpload', 'blockQuote', 'insertTable', 'mediaEmbed', 'undo', 'redo' ] }, language: 'en', image: { toolbar: [ 'imageTextAlternative', 'imageStyle:full', 'imageStyle:side' ] }, ckfinder: { uploadUrl: uploadApi, }, table: { contentToolbar: [ 'tableColumn', 'tableRow', 'mergeTableCells' ] }, licenseKey: '', } ) .then( editor => { window.editor = editor; } ) .catch( error => { console.error( 'Oops, something gone wrong!' ); console.error( 'Please, report the following error in the https://github.com/ckeditor/ckeditor5 with the build id and the error stack trace:' ); console.warn( 'Build id: k2i30chx32nf-8o65j7c6blw0' ); console.error( error ); } );
其实对于前端,就是给ckfinder配上一个url,就这么简单。
后台这块ASP.net,Java,PHP官方有文档,不过说实话一点都不友好。所以自给自足:
@PostMapping("/api/upload") private String uploadImage(@RequestParam MultipartFile[] upload) { String originalFileName = upload[0].getOriginalFilename(); String fileExtensionName = originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length()).toLowerCase();;//上传图片的文件扩展名 String newFileName = java.util.UUID.randomUUID().toString()+fileExtensionName; String uploadPath = imageUploaPath; String imageUrl = imageUploaPath + newFileName; File pathFile = new File(uploadPath); if (!pathFile.exists()) { // 如果路径不存在,创建 pathFile.mkdirs(); } try { File dest = new File(imageUrl); upload[0].transferTo(dest); } catch (IOException e) { } JSONObject jo = new JSONObject(); jo.put("uploaded", true); jo.put("url", newFileName); return jo.toJSONString(); }
代码是SpringBoot工程萃取出来的,已经删去了不必要的代码。尽量只展现这部分的有效信息。
最有用的信息是返回值格式:ckeditor5希望的格式其实是这样的json
{ "uploaded": true, "url": "xxxxx" }
这个是成功的返回格式。如果错误,则是下面:
{ "uploaded": false, "error": { "message": "xxxx" } }
代码中,imageUploadPath是@Autowired来的
@Value("${web.upload-path}") private String imageUploaPath;
在application.properties是这样:
web.upload-path=f:/imageUpload/ spring.mvc.static-path-pattern=/** spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
那个JSONObject用了Maven里面的json-simple
<!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple --> <dependency> <groupId>com.googlecode.json-simple</groupId> <artifactId>json-simple</artifactId> <version>1.1.1</version> </dependency>