欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSP中fckeditor控件表情修改以及文件上传(转)

程序员文章站 2022-05-20 18:48:51
...
(一)fckeditor控件表情修改

fckconfig.js中的后面几个参数控制表情,你可以将下面几个参数拷贝到myconfig.js,并进行修改就可以了。
FCKConfig.SmileyPath    = FCKConfig.BasePath + 'images/smiley/msn/' ; //图片的路径
//图片的名字(数组)
FCKConfig.SmileyImages  = ['aa.jpg','regular_smile.gif','sad_smile.gif','wink_smile.gif','teeth_smile.gif','confused_smile.gif','tounge_smile.gif','embaressed_smile.gif','omg_smile.gif','whatchutalkingabout_smile.gif','angry_smile.gif','angel_smile.gif','shades_smile.gif','devil_smile.gif','cry_smile.gif','lightbulb.gif','thumbs_down.gif','thumbs_up.gif','heart.gif','broken_heart.gif','kiss.gif','envelope.gif'] ;
FCKConfig.SmileyColumns = 8 ;// 每行显示的个数
FCKConfig.SmileyWindowWidth     = 320 ;//弹出窗口宽度
FCKConfig.SmileyWindowHeight    = 210 ;//弹出窗口高度
如果想修改弹出的标签页面可以去fckeditor/editor/dialog/fck_smiley.html文件。
//注释掉下面语句
//dialog.SetAutoSize( true ) ;//根据页面内容的大小,修改当前窗口的合适大小
以及修改下面样式
<!--将style类型更换
        <body style="overflow: hidden">
-->
<body style="overflow: auto">

(二)fckeditor控件实现文件文件上传

在web.xml中添加下面配置
    <servlet>
      <servlet-name>Connector</servlet-name>
        <servlet-class>
          net.fckeditor.connector.ConnectorServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>Connector</servlet-name>
      <url-pattern>
        /fckeditor/editor/filemanager/connectors/*
      </url-pattern>
在src目录下建立文件fckeditor.properties,并输入如下内容

connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl
重新发布项目,就可以实现服务器文件上传与浏览。


(三)fckeditor控件文件上传中文问题

上面虽然已经实现上传问题,单仍然存在中文乱码问题,具体解决办法如下:
自己新建一个ConnectorServlet,将源代码中原来ConnectorServlet的内容复制过来,并做简单修改。
图片名中文问题,解决方式如下:

(1)在dopost()方法中添加
    upload.setHeaderEncoding("utf-8");
(2)在创建文件夹时,也存在中文问题,需要在doget()方法中
String newFolderStr = UtilsFile.sanitizeFolderName(request.getParameter("NewFolderName"));
修改成
     String tmpStr=request.getParameter("NewFolderName");
     tmpStr=new String(tmpStr.getBytes("iso8859-1"),"utf-8");
     String newFolderStr = UtilsFile.sanitizeFolderName(tmpStr);

(3)虽然上面已经可以正常上传中文图片和创建中文文件夹,但是,中文图片却无法正常显示。
这里可以采用如下方式解决问题。上传以后采用其它非中文名称进行保存,这里采用
filename=UUID.randomUUID().toString()+"."+extension;来解决问题;
当然很多网站是采用当前日期生成对应文件名,这个也比较好。



具体代码如下
package jCuckoo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.fckeditor.connector.Messages;
import net.fckeditor.handlers.CommandHandler;
import net.fckeditor.handlers.ConnectorHandler;
import net.fckeditor.handlers.ExtensionsHandler;
import net.fckeditor.handlers.RequestCycleHandler;
import net.fckeditor.handlers.ResourceTypeHandler;
import net.fckeditor.response.UploadResponse;
import net.fckeditor.response.XmlResponse;
import net.fckeditor.tool.Utils;
import net.fckeditor.tool.UtilsFile;
import net.fckeditor.tool.UtilsResponse;
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;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ConnectorServlet extends HttpServlet {
    private static final long serialVersionUID = -5742008970929377161L;
    private static final Logger logger = LoggerFactory.getLogger(ConnectorServlet.class);
    public void init() throws ServletException, IllegalArgumentException {
        String realDefaultUserFilesPath = getServletContext().getRealPath(
                ConnectorHandler.getDefaultUserFilesPath());
        File defaultUserFilesDir = new File(realDefaultUserFilesPath);
        UtilsFile.checkDirAndCreate(defaultUserFilesDir);
        logger.info("ConnectorServlet successfully initialized!");
    }
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.debug("Entering ConnectorServlet#doGet");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/xml; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        String commandStr = request.getParameter("Command");
        String typeStr = request.getParameter("Type");
        String currentFolderStr = request.getParameter("CurrentFolder");
        logger.debug("Parameter Command: {}", commandStr);
        logger.debug("Parameter Type: {}", typeStr);
        logger.debug("Parameter CurrentFolder: {}", currentFolderStr);
        XmlResponse xr;
        if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
            xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
        else if (!CommandHandler.isValidForGet(commandStr))
            xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
        else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
            xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
        else if (!UtilsFile.isValidPath(currentFolderStr))
            xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
        else {
            CommandHandler command = CommandHandler.getCommand(commandStr);
            ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);
            String typePath = UtilsFile.constructServerSidePath(request, resourceType);
            String typeDirPath = getServletContext().getRealPath(typePath);
            File typeDir = new File(typeDirPath);
            UtilsFile.checkDirAndCreate(typeDir);
            File currentDir = new File(typeDir, currentFolderStr);
            if (!currentDir.exists())
                xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
            else {
                xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse
                        .constructResponseUrl(request, resourceType, currentFolderStr, true,
                                ConnectorHandler.isFullUrl()));
                if (command.equals(CommandHandler.GET_FOLDERS))
                    xr.setFolders(currentDir);
                else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
                    xr.setFoldersAndFiles(currentDir);
                else if (command.equals(CommandHandler.CREATE_FOLDER)) {
                  
                  String tmpStr=request.getParameter("NewFolderName");
                  tmpStr=new String(tmpStr.getBytes("iso8859-1"),"utf-8");
                  String newFolderStr = UtilsFile.sanitizeFolderName(tmpStr);
                 logger.debug("Parameter NewFolderName: {}", newFolderStr);
                    File newFolder = new File(currentDir, newFolderStr);
                    int errorNumber = XmlResponse.EN_UKNOWN;
                    if (newFolder.exists())
                        errorNumber = XmlResponse.EN_ALREADY_EXISTS;
                    else {
                        try {
                            errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
                                    : XmlResponse.EN_INVALID_FOLDER_NAME;
                        } catch (SecurityException e) {
                            errorNumber = XmlResponse.EN_SECURITY_ERROR;
                        }
                    }
                    xr.setError(errorNumber);
                }
            }
        }
        out.print(xr);
        out.flush();
        out.close();
        logger.debug("Exiting ConnectorServlet#doGet");
    }
    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.debug("Entering Connector#doPost");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        String commandStr = request.getParameter("Command");
        String typeStr = request.getParameter("Type");
        String currentFolderStr = request.getParameter("CurrentFolder");
        logger.debug("Parameter Command: {}", commandStr);
        logger.debug("Parameter Type: {}", typeStr);
        logger.debug("Parameter CurrentFolder: {}", currentFolderStr);
        UploadResponse ur;
        // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
        // are empty
        if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
            commandStr = "QuickUpload";
            currentFolderStr = "/";
        }
        if (!RequestCycleHandler.isEnabledForFileUpload(request))
            ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
                    Messages.NOT_AUTHORIZED_FOR_UPLOAD);
        else if (!CommandHandler.isValidForPost(commandStr))
            ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
        else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
            ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
        else if (!UtilsFile.isValidPath(currentFolderStr))
            ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
        else {
            ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr);
            String typePath = UtilsFile.constructServerSidePath(request, resourceType);
            String typeDirPath = getServletContext().getRealPath(typePath);
            File typeDir = new File(typeDirPath);
            UtilsFile.checkDirAndCreate(typeDir);
            File currentDir = new File(typeDir, currentFolderStr);
            if (!currentDir.exists())
                ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
            else {
                String newFilename = null;
                FileItemFactory factory = new DiskFileItemFactory();
                ServletFileUpload upload = new ServletFileUpload(factory);
               
                //此处修改
                upload.setHeaderEncoding("utf-8");
                try {
                    List<FileItem> items = upload.parseRequest(request);
                    // We upload only one file at the same time
                    FileItem uplFile = items.get(0);
                    String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
                    String filename = FilenameUtils.getName(rawName);
                    String baseName = FilenameUtils.removeExtension(filename);
                    String extension = FilenameUtils.getExtension(filename);
                    if (!ExtensionsHandler.isAllowed(resourceType, extension))
                        ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                    else {
                        // 将文件名字进行转换,换掉原先中文名字,当然可以采用日期产生文件的名字。
                        filename=UUID.randomUUID().toString()+"."+extension;
                        File pathToSave = new File(currentDir, filename);
                        int counter = 1;
                        while (pathToSave.exists()) {
                            newFilename = baseName.concat("(").concat(String.valueOf(counter))
                                    .concat(")").concat(".").concat(extension);
                            pathToSave = new File(currentDir, newFilename);
                            counter++;
                        }
                        if (Utils.isEmpty(newFilename))
                            ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse
                                    .constructResponseUrl(request, resourceType, currentFolderStr,
                                            true, ConnectorHandler.isFullUrl()).concat(filename));
                        else
                            ur = new UploadResponse(UploadResponse.SC_RENAMED,
                                    UtilsResponse.constructResponseUrl(request, resourceType,
                                            currentFolderStr, true, ConnectorHandler.isFullUrl())
                                            .concat(newFilename), newFilename);
                        // secure image check
                        if (resourceType.equals(ResourceTypeHandler.IMAGE)
                                && ConnectorHandler.isSecureImageUploads()) {
                            if (UtilsFile.isImage(uplFile.getInputStream()))
                                uplFile.write(pathToSave);
                            else {
                                uplFile.delete();
                                ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
                            }
                        } else
                            uplFile.write(pathToSave);
                    }
                } catch (Exception e) {
                    ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
                }
            }
        }
        out.print(ur);
        out.flush();
        out.close();
        logger.debug("Exiting Connector#doPost");
    }
}
然后将web.xml中的servlet进行修改,具体修改如下:

    <servlet>
      <servlet-name>Connector</servlet-name>
        <servlet-class>
          jCuckoo.ConnectorServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>Connector</servlet-name>
      <url-pattern>
        /fckeditor/editor/filemanager/connectors/*
      </url-pattern>
    </servlet-mapping>
重新部署,发布就可以实现该功能。


转载:http://blog.csdn.net/guoquanyou/article/details/3562052
相关标签: fckeditor jsp