使用ckeditor5上传图片

1. CKEditor是什么?

  1. 它是一款自认为比较好看的编辑器,界面简洁,功能能强大。
  2. CKEditor5的用法和CKEditor4.0版本完全不同,而网上几乎没有比较完整的教程,而官网教程又都是英语,比较难入门,所以在使用CKEditor5的时候踩了许多坑,把自己踩坑过程简单写一下。

2.上传图片

官网上也有上传出片的demo,但是全英文的对人太不友好了,下面讲一下具体

将下载好的ckeditor的文件解压放在你要使用的项目下:

20190427230916769

然后在你要用的界面导入ckeditor.js

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ckeditor5</title>
<style type="text/css">
.ck.ck-reset.ck-editor{
	width:600px;
}
.ck-content {
    min-height: 300px;
}
</style>
<script src="ckeditor5/ckeditor.js"></script>
</head>
<body>
	<textarea id="editor" rows="" cols=""></textarea>
 
	<script type="text/javascript">
		let edit;
		ClassicEditor
		.create( document.querySelector( '#editor' ), {
		    language:"zh-cn",
		    ckfinder: {
		        uploadUrl: "对应的请求地址"
		    }
		})
		.then( editor => {
		    edit=editor;
		} )
		.catch( error => {
		    console.error( error );
		} );
 
</script>
</body>
</html>

然后在用js生成编辑器,js想要获得编辑器里的数据只能通过

//这里的editor是上面定的一个全局变量,生成控件的时候赋的值

uploadUrl 即是你对应的请求地址
editor.getData();

这里顺便在附上后端处理的代码java:

package servlet;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
 
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 
import com.google.gson.Gson;
 
 
/**
 * 处理图片上传
 * @author HarryZhang
 *
 */
@WebServlet("/uploadimg")
public class UploadImg extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.getWriter().print(ckEditorUploadImage(request));
	}
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
 
	
	
	public String ckEditorUploadImage(HttpServletRequest request) {
		String path = request.getContextPath();
		String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
	    if(ServletFileUpload.isMultipartContent(request)) {
	        DiskFileItemFactory factory = new DiskFileItemFactory();
	        ServletContext context = request.getServletContext();
	        factory.setRepository(new File(request.getRealPath("/images/upload")));
	        factory.setSizeThreshold(100000000);
 
	        ServletFileUpload upload = new ServletFileUpload(factory);
	        upload.setFileSizeMax(1024*1024*10);
	        upload.setSizeMax(1024*1024*100);
 
	        List<FileItem> items = null;
	        try {
	            items = upload.parseRequest(request);
	        } catch (FileUploadException e) {
	            e.printStackTrace();
	        }
 
	        Iterator<FileItem> iter = items.iterator();
	        String localFileName = null;
	        while(iter.hasNext()) {
	            FileItem item = iter.next();
	            if(!"upload".equals(item.getFieldName())) {
	                continue;
	            }
	            String str = item.getName();
	            String[] strarray=str.split("\\."); 
	            String originalName = getRandomString(10) + "."+ strarray[strarray.length-1];
	            localFileName = System.currentTimeMillis() + "-" + originalName;
	            String localFilePath = request.getRealPath("/images/upload/") +localFileName;
	            File prjimg=new File(""+localFileName);
	            File localFile = new File(localFilePath);
	            try {
	                if(!localFile.getParentFile().exists()) {
	                    localFile.getParentFile().mkdirs();
	                }
	                if(!localFile.exists()) {
	                    localFile.createNewFile();
	                }
	                item.write(localFile);
	                item.write(prjimg);
	            } catch (IOException e) {
	                e.printStackTrace();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	        System.out.println("stored local file name: " + localFileName);
	        System.out.println("returned url: " + basePath+"images/upload/"+localFileName);
	        System.out.println(generateResult(true, basePath+"images/upload/"+localFileName));
	        return generateResult(true, basePath+"images/upload/"+localFileName);
	    }
	    System.out.println(generateResult(false, "/"));
	    return generateResult(false, "/");
	}
	private String generateResult(boolean uploaded, String relativeUrl){
		HashMap<String, String> result = new HashMap<String, String>();
        result.put("uploaded", uploaded + "");
        result.put("url", relativeUrl);
        
        return new Gson().toJson(result);
    }
	public static String getRandomString(int length){
	     String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	     Random random=new Random();
	     StringBuffer sb=new StringBuffer();
	     for(int i=0;i<length;i++){
	       int number=random.nextInt(62);
	       sb.append(str.charAt(number));
	     }
	     return sb.toString();
	 }	
}

这里返回的json里包含url可以做一个上传图片后回显的功能,