ckeditor5上传图片至服务器(解决自带代码上传失败问题)

直接开始正题

1、前端代码

加载JS文件

页面内js

HTML代码

2、通过Java搭建Servlet服务完成后端上传(实现随机文件名)

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.jws.WebService;
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 javax.servlet.http.HttpSession;

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 net.sf.json.JSON;
import net.sf.json.JSONObject;


@WebServlet("/index")
public class aa extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ckEditorUploadImage(req);
	}
	
	private static final String CK_IMAGE_PATH = File.separator + "uploadImage";
	
	public JSON ckEditorUploadImage(HttpServletRequest request) {
	    if(ServletFileUpload.isMultipartContent(request)) {
	        DiskFileItemFactory factory = new DiskFileItemFactory();
	        ServletContext context = request.getServletContext();
	        factory.setRepository(new File("D:/updata/"));
	        factory.setSizeThreshold(100000000);

	        ServletFileUpload upload = new ServletFileUpload(factory);
	        upload.setFileSizeMax(1024*1024*10);
	        upload.setSizeMax(1024*1024*100);

	        List items = null;
	        try {
	            items = upload.parseRequest(request);
	        } catch (FileUploadException e) {
	            e.printStackTrace();
	        }

	        Iterator 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 = "D:/upload/"+ localFileName;
	            File localFile = new File(localFilePath);
	            try {
	                if(!localFile.getParentFile().exists()) {
	                    localFile.getParentFile().mkdirs();
	                }
	                if(!localFile.exists()) {
	                    localFile.createNewFile();
	                }
	                item.write(localFile);
	            } catch (IOException e) {
	                e.printStackTrace();
	            } catch (Exception e) {
	                e.printStackTrace();
	            }
	        }
	        String imageContextPath = "/upload/" + localFileName;
	        System.out.println("stored local file name: " + localFileName);
	        System.out.println("returned url: " + imageContextPath);
	        System.out.println(generateResult(true, imageContextPath));
	        return generateResult(true, imageContextPath);
	    }
	    System.out.println(generateResult(false, "/"));
	    return generateResult(false, "/");
	}
	private JSON generateResult(boolean uploaded, String relativeUrl){
		HashMap result = new HashMap();
        result.put("uploaded", uploaded + "");
        result.put("url", relativeUrl);

        return new JSONObject().fromObject(result);
    }
	public static String getRandomString(int length){
	     String str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	     Random random=new Random();
	     StringBuffer sb=new StringBuffer();
	     for(int i=0;i

3、配置Tomcat

ckeditor5上传图片至服务器(解决自带代码上传失败问题)_第1张图片

在D盘下新建两个文件夹 名字:“updata”、“upload”

截至目前代码已经能够成功上传图片了(传说ckeditor5本身带的上传服务器的代码由于返回值和解析需求不匹配导致上传失败)

附加

如何获取编辑器内容!!!

JS

myEditor.getData();

的返回值就是编辑器生成的HTML代码 下次如果要编辑 直接把上次保存的内容放在

懂了吧。

你可能感兴趣的:(简单的日常)