ckeditor 实现 servlet 图片上传 配置

整个源码上传在  http://download.csdn.net/source/3539767

注意有一点小bug【不支持中文图片上传】

web.xml 的相关配置

其中baseDir是文件上传后的目录。

<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>false</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>

servlet的完整源码

package ckeditor;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
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.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初始化方法
     */
    @SuppressWarnings("unchecked")
    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.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");
        out.println("<script type=\"text/javascript\">");
        out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
                + ",‘" + fileUrl + "‘,‘‘" + ")");
        out.println("</script>");
        out.flush();
        out.close();
        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;
    }

}

测试页面

<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    pageContext.setAttribute("path",path);
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="/ckeditor/ckeditor/ckeditor.js"></script>
<title>CKEditor</title>
<style type="text/css">
* {
    font-family: "宋体";
    font-size: 14px
}
</style>

</head>
<body>
<form id="form1" name="form1" method="post" action="/ckeditor/display.jsp">
<table width="650" height="400" border="0" align="center">

    <tr>
        <td>主题:</td>
        <td><input name="title" type="text" id="title" size="80"
            maxlength="80" /></td>
    </tr>
    <tr>
        <td valign="top">内容:</td>
        <td><textarea cols="80" id="content" name="content">
      </textarea>
          <script type="text/javascript">
            CKEDITOR.replace(‘content‘,{filebrowserUploadUrl : ‘${path}/ckeditor/uploader?Type=File‘,
            filebrowserImageUploadUrl : ‘${path}/ckeditor/uploader?Type=Image‘,
            filebrowserFlashUploadUrl : ‘${path}/ckeditor/uploader?Type=Flash‘
            });
        </script></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" name="Submit" value="提交" /> <input
            type="reset" name="Reset" value="重置" /></td>
    </tr>
</table>
</form>
</body>
</html>

display.jsp

<%@page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Display Content</title>
</head>
<%request.setCharacterEncoding("UTF-8"); %>
<center>
<table width="600" border="0" bordercolor="000000"
    style="table-layout: fixed;">
    <tr>
        <td width="100" bordercolor="ffffff">主题:</td>
        <td width="500" bordercolor="ffffff">${param.title}</td>
    </tr>
    <tr>
        <td valign="top" bordercolor="ffffff">内容:</td>
        <td valign="top" bordercolor="ffffff">${param.content}</td>
    </tr>
</table>
</center>
</html>

原文地址:https://www.cnblogs.com/xylic1128/p/9267894.html

时间: 2024-10-08 22:59:26

ckeditor 实现 servlet 图片上传 配置的相关文章

SpringMVC:学习笔记(10)——整合Ckeditor且实现图片上传

搞清楚路径位置 配置CKEDITOR 精简文件 解压之后可以看到ckeditor/lang下面有很多语言的js,如果不需要那么多种语言的,可以只剩下en.js,zh.js,zh-cn.js 图片上传时图像信息中的预览会显示一堆英文信息,会干扰预览.找到ckeditor/plugins/image/dialogs/image.js,搜索"d.config.image_previewText"就能找到这段鸟语了,(d.config.image_previewText||")引号中

Java Servlet图片上传至指定文件夹并显示图片

在学习Servlet过程中,针对图片上传做了一个Demo,实现的功能是:在a页面上传图片,点击提交后,将图片保存到服务器指定路径(D:/image):跳转到b页面,b页面读取展示绝对路径(D:/image)的图片.主要步骤如下: 步骤一:上传页面uploadphoto.jsp 需要注意两个问题: 1.form 的method必须是post的,get不能上传文件, 还需要加上enctype="multipart/form-data" 表示提交的数据是二进制文件. 2.需要提供type=&

ueditor图片上传配置

ueditor图片上传配置文件为ueditor/php/config.json /* 上传图片配置项 */ "imageActionName": "uploadimage", /* 运行上传图片的action名称 */ "imageFieldName": "upfile", /* 提交的图片表单名称 */ "imageMaxSize": 2048000, /* 上传限制大小,单位B */ "ima

一个简单的安卓+Servlet图片上传例子

例子比较 简单,服务端为Java Web Servlet,doPost方法中接收图片并保存,然后将保存的图片名返回给客户端,关键代码: @SuppressWarnings("deprecation") public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { request.setCharacterEncoding(

Ueditor 1.4.3 图片上传配置

1. 在工程中引入 ueditor ueditor其实就是一个js插件,所以一般将其,放到工程的js目录下面 如上图所示的目录,直接将下载下来的ueditor发到js目录中,特别要注意的是此时要吧 jsp 中的 lib 中的这几个包全部复制到 WEB-INF下的lib目录中,特别注意,在复制时前4个jar包可能工程中已经存在了,就一定不要引入重复的jar包,否则就会导致jar包冲突,一定要仔细 2. 在jsp文件中使用ueditor 2.1 在页面中引入 ueditor <script type

在ASP.NET项目中使用CKEditor +CKFinder实现图片上传功能

前言 之前的项目中一直使用的是FCKeditor,昨天突然有个想法:为什么不试一下新的CKEditor呢?于是花了大半天的时间去学习它的用法,现在把我的学习过程与大家分享一下. 谈起FCKeditor,相信没几个Web程序员不知道的吧.不过,官方已经停止了该产品的更新,其最新版是2.6.6,于2010年2月15日发布. 取代FCKeditor的产品叫CKEditor(Content And Knowledge Editor),与其说是对FCKeditor的升级,不如说是全新的一个产品.相比FCK

Servlet图片上传

package com.servlet; import java.io.DataInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.Http

ckeditor4.7配置图片上传

ckeditor作为老牌的优秀在线编辑器,一直受到开发者的青睐. 这里我们讲解下 ckeditor最新版本4.7的图片上传配置. https://ckeditor.com/ 官方 进入下载 https://ckeditor.com/download 我们下载完整版 默认本地上传没有开启: 找到ckeditor/plugins/image/dialogs/image.js文件 打开 然后搜索 id:"Upload",hidden   默认值是!0 我们改成0即可 刷新页面,点击那个上传图

ckedit 图片上传 php

分享ckedit的使用.直接码出来 <input type="hidden" name="id" id="id" value="<?php echo $data['id'];?>"> <div style="display:none" > <textarea id="data"><?php echo $data['content'];