CKeditor上传图片 实现所见即所得界面

迟了好多天的分享,CKeditor这个编辑器虽然不错,但也真苟啊,搞图片上传这个功能,快给我搞佛系了,话不多说,上代码

1、首先去官网下载一个full的版本,我用的是CKeditor 4.13,解压之后放在webcontent下边

 

2、在你要用的界面添加下这个

引入ckeditor编辑器

 

 

 3.还有这个,这是加载文本编辑器的

<textarea class="form-control" id="editor" name="content" style="color:#8a8a8a;width: 100%; height: 482px; display: block;"></textarea>

     <script type="text/javascript">

            CKEDITOR.replace('editor',{filebrowserUploadUrl : '${path}/ckeditor/uploader?Type=File',
 
            filebrowserImageUploadUrl : '${path}/ckeditor/uploader?Type=Image',

            filebrowserFlashUploadUrl : '${path}/ckeditor/uploader?Type=Flash'
 
            });
        </script>

4.

 

 这个是你自己的路径,

 

 5.这个是那个上传链接里边的ckeditor文件夹(并不是下载的文本编辑器的文件),处理上传的图片文件, 

CKEditorUploadServlet.java

 

package ckeditor;


import java.io.*;  
import java.text.SimpleDateFormat;  
import java.util.*;  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
import org.apache.commons.fileupload.FileItem;  
import org.apache.commons.fileupload.FileItemFactory;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
public class CKEditorUploadServlet extends HttpServlet {  
    private static String baseDir;// CKEditor根目录
    private static boolean debug = false;// 是否debug模式  
    private static boolean enabled = false;// 是否开启CKEditor上传  
    private static Hashtable allowedExtensions;//允许的上传文件扩展名  
    private static Hashtable deniedExtensions;// 阻止的上传文件扩展名  
    private static SimpleDateFormat dirFormatter;//目录命名格式:yyyyMM  
    private static SimpleDateFormat fileFormatter;//文件命名格式:yyyyMMddHHmmssSSS  
    /** 
     * Servlet初始化方法 
     */  
    public void init() throws ServletException {  
        // 从web.xml中读取debug模式  
        debug = (new Boolean(getInitParameter("debug"))).booleanValue();  
        if (debug)  
            System.out.println("\r\n---- SimpleUploaderServlet initialization started ----");  
     // 格式化目录和文件命名方式 
        dirFormatter = new SimpleDateFormat("yyyyMM");  
        fileFormatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");  
        // 从web.xml中获取根目录名称  
        baseDir = getInitParameter("baseDir");  
        // 从web.xml中获取是否可以进行文件上传  
        enabled = (new Boolean(getInitParameter("enabled"))).booleanValue();  
        if (baseDir == null)  
            baseDir = "/UserFiles/";  
        String realBaseDir = getServletContext().getRealPath(baseDir);  
        File baseFile = new File(realBaseDir);  
        if (!baseFile.exists()) {  
            baseFile.mkdirs();  
        }  
        // 实例化允许的扩展名和阻止的扩展名  
        allowedExtensions = new Hashtable(3);  
        deniedExtensions = new Hashtable(3);  
        // 从web.xml中读取配置信息  
        allowedExtensions.put("File",  
        stringToArrayList(getInitParameter("AllowedExtensionsFile")));  
        deniedExtensions.put("File",  
        stringToArrayList(getInitParameter("DeniedExtensionsFile")));  
        allowedExtensions.put("Image",  
    stringToArrayList(getInitParameter("AllowedExtensionsImage")));  
        deniedExtensions.put("Image",           stringToArrayList(getInitParameter("DeniedExtensionsImage")));  
        allowedExtensions.put("Flash",          stringToArrayList(getInitParameter("AllowedExtensionsFlash")));  
        deniedExtensions.put("Flash",           stringToArrayList(getInitParameter("DeniedExtensionsFlash")));  
        if (debug)  
            System.out.println("---- SimpleUploaderServlet initialization completed ----\r\n");  
    }  
    public void doGet(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        doPost(request, response);  
    }  
    public void doPost(HttpServletRequest request, HttpServletResponse response)  
            throws ServletException, IOException {  
        if (debug)  
            System.out.println("--- BEGIN DOPOST ---");  
        //response.setContentType("text/html; charset=UTF-8");
        response.setContentType("text/json; charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");  
        PrintWriter out = response.getWriter();  
        // 从请求参数中获取上传文件的类型:File/Image/Flash  
        String typeStr = request.getParameter("Type");  
        if (typeStr == null) {  
            typeStr = "File";  
        }  
        if (debug)  
            System.out.println(typeStr);  
        // 实例化dNow对象,获取当前时间  
        Date dNow = new Date();  
        // 设定上传文件路径  
        String currentPath = baseDir + typeStr + "/"  
                + dirFormatter.format(dNow);  
        // 获得web应用的上传路径  
        String currentDirPath = getServletContext().getRealPath(currentPath);  
        // 判断文件夹是否存在,不存在则创建
        File dirTest = new File(currentDirPath);  
        if (!dirTest.exists()) {  
            dirTest.mkdirs();  
        }  
        // 将路径前加上web应用名  
        currentPath = request.getContextPath() + currentPath;  
        if (debug)  
            System.out.println(currentDirPath);  
        // 文件名和文件真实路径  
        String newName = "";  
        String fileUrl = "";  
        if (enabled) {  
            // 使用Apache Common组件中的fileupload进行文件上传  
            FileItemFactory factory = new DiskFileItemFactory();  
            ServletFileUpload upload = new ServletFileUpload(factory);  
            try {  
                List items = upload.parseRequest(request);  
                Map fields = new HashMap();  
                Iterator iter = items.iterator();  
                while (iter.hasNext()) {  
                    FileItem item = (FileItem) iter.next();  
                    if (item.isFormField())  
                        fields.put(item.getFieldName(), item.getString());  
                    else  
                        fields.put(item.getFieldName(), item);  
                }  
                // CEKditor中file域的name值是upload 
                FileItem uplFile = (FileItem) fields.get("upload");  
             // 获取文件名并做处理  
                String fileNameLong = uplFile.getName();  
                fileNameLong = fileNameLong.replace('\\', '/');  
                String[] pathParts = fileNameLong.split("/");  
                String fileName = pathParts[pathParts.length - 1];  
                // 获取文件扩展名  
                String ext = getExtension(fileName);  
                // 设置上传文件名  
                fileName = fileFormatter.format(dNow) + "." + ext;  
                // 获取文件名(无扩展名)   
                String nameWithoutExt = getNameWithoutExtension(fileName);  
                File pathToSave = new File(currentDirPath, fileName);  
                fileUrl = currentPath + "/" + fileName;  
                if (extIsAllowed(typeStr, ext)) {  
                    int counter = 1;  
                    while (pathToSave.exists()) {  
                        newName = nameWithoutExt + "_" + counter + "." + ext;  
                        fileUrl = currentPath + "/" + newName;  
                        pathToSave = new File(currentDirPath, newName);  
                        counter++;  
                    }  
                    uplFile.write(pathToSave);  
                } else {  
                    if (debug)  
                        System.out.println("无效的文件类型 " + ext);  
                }  
            } catch (Exception ex) {  
                if (debug)  
                    ex.printStackTrace();  
            }  
        } else {  
            if (debug)  
                System.out.println("未开启CKEditor上传功能");  
        }  
        // CKEditorFuncNum是回调时显示的位置,这个参数必须有  
        String callback = request.getParameter("CKEditorFuncNum");  
        System.out.println(request.getParameter("CKEditorFuncNum"));
        System.out.println(request.getParameter("CKEditor"));
        System.out.println(request.getParameter("langCode"));
        
        String json="{\"uploaded\" : 1, \"fileName\" : \"fileNameStr\", \"url\":\""+fileUrl+"\" , \"error\" : { \"message\":\"successful\" } }";
        out.println(json);
        out.flush();  
         out.close();

        
        
       // out.println("<script type=\"text/javascript\">");  
      //  out.println("window.parent.CKEDITOR.tools.callFunction(" + "'1'"  
               // + ",'" + fileUrl + "',' '涓婁紶鎴愬姛fdfdfdf''" + ")");  
      //  out.println("</script>");  
      //  out.flush();  
       // out.close();  
        System.out.println("callback-->"+callback);
        System.out.println("fileUrl-->"+json);
       // response.sendRedirect(request.getContextPath()+"/ATextDao?a="+fileUrl);
        if (debug)  
            System.out.println("--- END DOPOST ---");  
    }  
    /** 
     * 获取文件名的方法 
     */  
    private static String getNameWithoutExtension(String fileName) {  
        return fileName.substring(0, fileName.lastIndexOf("."));  
    }  
    /** 
     * 获取扩展名的方法 
     */  
    private String getExtension(String fileName) {  
        return fileName.substring(fileName.lastIndexOf(".") + 1);  
    }  
    /** 
     * 字符串像ArrayList转化的方法 
     */   
    private ArrayList stringToArrayList(String str) {  
        if (debug)  
            System.out.println(str);  
        String[] strArr = str.split("\\|");  
        ArrayList tmp = new ArrayList();  
        if (str.length() > 0) {  
            for (int i = 0; i < strArr.length; ++i) {  
                if (debug)  
                    System.out.println(i + " - " + strArr[i]);  
                tmp.add(strArr[i].toLowerCase());  
            }  
        }  
        return tmp;  
    }  
    /** 
     * 判断扩展名是否允许的方法 
     */   
    private boolean extIsAllowed(String fileType, String ext) {  
        ext = ext.toLowerCase();  
        ArrayList allowList = (ArrayList) allowedExtensions.get(fileType);  
        ArrayList denyList = (ArrayList) deniedExtensions.get(fileType);  
        if (allowList.size() == 0) {  
            if (denyList.contains(ext)) {  
                return false;  
            } else {  
                return true;  
            }  
        }  
        if (denyList.size() == 0) {  
            if (allowList.contains(ext)) {  
                return true;  
            } else {  
                return false;  
            }  
        }  
        return false;  
    }  
}  

 

 web.xml

<servlet>
    <servlet-name>SimpleUploader</servlet-name>
    <servlet-class>ckeditor.CKEditorUploadServlet</servlet-class>
    <init-param>
      <param-name>baseDir</param-name>
      <param-value>/UserFiles/</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>enabled</param-name>
      <param-value>true</param-value>
    </init-param>
    <init-param>
      <param-name>AllowedExtensionsFile</param-name>
      <param-value></param-value>
    </init-param>
    <init-param>
      <param-name>DeniedExtensionsFile</param-name>
      <param-value>  
                html|htm|php|php2|php3|php4|php5|phtml|pwml|inc|asp|aspx|ascx|jsp|cfm|cfc|pl|bat|exe|com|dll|vbs|js|reg|cgi|htaccess|asis|ftl  
            </param-value>
    </init-param>
    <init-param>
      <param-name>AllowedExtensionsImage</param-name>
      <param-value>jpg|gif|jpeg|png|bmp</param-value>
    </init-param>
    <init-param>
      <param-name>DeniedExtensionsImage</param-name>
      <param-value></param-value>
    </init-param>
    <init-param>
      <param-name>AllowedExtensionsFlash</param-name>
      <param-value>swf|fla</param-value>
    </init-param>
    <init-param>
      <param-name>DeniedExtensionsFlash</param-name>
      <param-value></param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>SimpleUploader</servlet-name>
    <url-pattern>/ckeditor/uploader</url-pattern>
  </servlet-mapping>

这样就能上传到你这个项目的文件夹下了,命令行有地址输出,

至于所见即所得,html代码存入数据库就行,文本编辑器这自己写个form表单,写个servlet加入数据库就行了

 

 

posted @ 2020-02-18 21:11  萌萌程序猿  阅读(412)  评论(0编辑  收藏  举报