`
huibin
  • 浏览: 737568 次
  • 性别: Icon_minigender_1
  • 来自: 郑州
社区版块
存档分类
最新评论

(转)FCKeditor2.6在线文本编辑器

阅读更多
多文件上传:

Struts2也可以很方便地实现多文件上传。

         在输入表单域增加多个文件域:multifileupload.jsp

              



<%@ page language="java" contentType="text/html; charset=UTF-8"%>

<%@ taglib uri="/struts-tags" prefix="s" %>

<html>

<head>

    <title>多文件上传</title>

</head>

<body>

    <font color="red"><s:fielderror/></font>

    <form action="multiFileUpload.action" method="POST" enctype="multipart/form-data">

        文件标题:<input type="text" name="title" size="50" value="${param.title }"/><br/>

       <!-- 设置二个文件域,名字相同 -->

        选择第一个文件:<input type="file" name="upload" size="50"/><br/>

        选择第二个文件:<input type="file" name="upload" size="50"/><br/>

       <input type="submit" value=" 上传 "/>      

    </form>

</body>

</html>



         在Action类中用数组来封装该多个文件域:MultiFileUploadAction.java

              



package org.qiujy.web.struts2;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**

*处理多文件上传的Action类

*

*@authorqiujy

*@version1.0

*/

publicclass MultiFileUploadAction extends ActionSupport {

    privatestaticfinalintBUFFER_SIZE = 16 * 1024;

    // 文件标题

    private String title;

    // 用File数组来封装多个上传文件域对象

    private File[] upload;

    // 用String数组来封装多个上传文件名

    private String[] uploadFileName;

    // 用String数组来封装多个上传文件类型

    private String[] uploadContentType;

    // 保存文件的目录路径(通过依赖注入)

    private String savePath;

    //以下为所有属性的getter和setter。省略。。。

    // 自己封装的一个把源文件对象复制成目标文件对象

    privatestaticvoid copy(File src, File dst) {

        InputStream in = null;

        OutputStream out = null;

        try {

            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);

            out = new BufferedOutputStream(new FileOutputStream(dst),

                    BUFFER_SIZE);

            byte[] buffer = newbyte[BUFFER_SIZE];

            int len = 0;

            while ((len = in.read(buffer)) > 0) {

                out.write(buffer, 0, len);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (null != in) {

                try {

                    in.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (null != out) {

                try {

                    out.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    @Override

    public String execute() throws Exception {

        File[] srcFiles = this.getUpload();

        // 处理每个要上传的文件

        for (int i = 0; i < srcFiles.length; i++) {

            // 根据服务器的文件保存地址和原文件名创建目录文件全路径

            String dstPath = ServletActionContext.getServletContext()

                    .getRealPath(this.getSavePath())

                    + "\\" + this.getUploadFileName()[i];

            File dstFile = new File(dstPath);

            this.copy(srcFiles[i], dstFile);

        }

        returnSUCCESS;

    }

}



运行结果:

5.    Struts2的文件下载:

文件下载相对简单一些,一般只需在页面上提供一个超链接,该链接的href属性等于要下载文件的文件名就行了。但当文件名有中文时,就会导致失败;或者要在用户下载前进行权限判断,这时用Struts2提供的文件下载功能就能简单的解决这些问题。


2009-05-25

--------------------------------------------------------------------------------

Love begins with a smile, grows with a kiss, ends with a tear. When you were born, you were crying and everyone around you was smiling. Live your life so that when you die, you're the one smiling and everyone around you is crying.20:49 | 添加评论 | 固定链接 | 写入日志[Struts]转:Struts2.0上传文件(2)
       在这个文件中跟以前配置唯一不同的是给action配置了一个<param …/>元素,用来为该Action的savePath属性动态注入值。
web.xml中的配置跟以前的应用一样。说明一点:好多网络文章说Struts2上传时要在web.xml中配置一个名为 ActionContextUp的过滤器,说是有一些莫名的错误,可是是我用了Struts2新版本2.0.9GA版,测了n次,没出现什么问题,所以没配置。

2.4.    运行调试:

运行前要在根目录下创建一个名为upload的文件夹,用来存放上传后的文件。

上传结果:

3.    文件类型及错误输出:

Struts2提供了一个文件上传的拦截器(名为fileUpload),通过配置这个拦截器能轻松地实现文件类型的过滤。

在上例中,若要配置上传的文件只能是一些普通的图片文件格式:image/bmp、image/png、image/gif、image/jpeg、image/jpg等,则可在struts.xml文件中按如下方式配置:



               

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.custom.i18n.resources" value="messages"/>

    <package name="fileUploadDemo" extends="struts-default">

        <action name="fileUpload"

            class="org.qiujy.web.struts2.FileUploadAction">

            <interceptor-ref name="fileUpload">

              <!-- 配置允许上传的文件类型,多个用","分隔 -->

              <param name="allowedTypes">

          image/bmp,image/png,image/gif,image/jpeg,image/jpg



,image/x-png, image/pjpeg

              </param>

              <!-- 配置允许上传的文件大小,单位字节 -->

              <param name="maximumSize">102400</param>

           </interceptor-ref>

           <interceptor-ref name="defaultStack" />

            <!-- 动态设置Action中的savePath属性的值 -->

            <param name="savePath">/upload</param>

            <result name="input">/index.jsp</result>

            <result name="success">/showupload.jsp</result>

        </action>

    </package>

</struts>



如果上传文件失败,系统返回到input对应的页面,要在input对应的页面输出文件过滤失败信息,可以在input对应的页面中增加 <s:fielderror/>来显示错误信息。

运行调试:

结果:

         显然,这样的提示不太友好,应用使用国际化信息。在国际化资源文件中添加如下三句:

              

#更改上传文件类型不允许的提示信息

struts.messages.error.content.type.not.allowed=文件上传失败:你要上传的文件类型不允许

#更改上传文件太大的提示信息

struts.messages.error.file.too.large=文件上传失败:你要上传的文件太大

#文件上传其它错误信息

struts.messages.error.uploading=文件上传失败:发生内部错误

         别忘了要用native2ascii.exe进行编码转换哦。再运行调试:

另外,在控制台会看到一条消息:

              

Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir

Removing file upload D:\tomcat6.0.13\work\Catalina\localhost\fileload_struts2\upload__4b616fd1_115a3d5d9dc__7fff_00000005.tmp

第一个说是找不以struts.multipart.saveDir,即没有指定临时文件夹,这个很好解决,只需指定一个struts.multipart.saveDir常量值为某个目录来解决。第二个说正在删除一个临时文件,这个临时文件是上传过程中产生的,属正常。




2009-05-25

--------------------------------------------------------------------------------

Love begins with a smile, grows with a kiss, ends with a tear. When you were born, you were crying and everyone around you was smiling. Live your life so that when you die, you're the one smiling and everyone around you is crying.20:49 | 添加评论 | 固定链接 | 写入日志[Struts]转:Struts2.0上传文件(2)
       在这个文件中跟以前配置唯一不同的是给action配置了一个<param …/>元素,用来为该Action的savePath属性动态注入值。

web.xml中的配置跟以前的应用一样。说明一点:好多网络文章说Struts2上传时要在web.xml中配置一个名为 ActionContextUp的过滤器,说是有一些莫名的错误,可是是我用了Struts2新版本2.0.9GA版,测了n次,没出现什么问题,所以没配置。

2.4.    运行调试:

运行前要在根目录下创建一个名为upload的文件夹,用来存放上传后的文件。

上传结果:

3.    文件类型及错误输出:

Struts2提供了一个文件上传的拦截器(名为fileUpload),通过配置这个拦截器能轻松地实现文件类型的过滤。

在上例中,若要配置上传的文件只能是一些普通的图片文件格式:image/bmp、image/png、image/gif、image/jpeg、image/jpg等,则可在struts.xml文件中按如下方式配置:



               

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <constant name="struts.custom.i18n.resources" value="messages"/>

    <package name="fileUploadDemo" extends="struts-default">

        <action name="fileUpload"

            class="org.qiujy.web.struts2.FileUploadAction">

            <interceptor-ref name="fileUpload">

              <!-- 配置允许上传的文件类型,多个用","分隔 -->

              <param name="allowedTypes">

          image/bmp,image/png,image/gif,image/jpeg,image/jpg



,image/x-png, image/pjpeg

              </param>

              <!-- 配置允许上传的文件大小,单位字节 -->

              <param name="maximumSize">102400</param>

           </interceptor-ref>

           <interceptor-ref name="defaultStack" />

            <!-- 动态设置Action中的savePath属性的值 -->

            <param name="savePath">/upload</param>

            <result name="input">/index.jsp</result>

            <result name="success">/showupload.jsp</result>

        </action>

    </package>

</struts>



如果上传文件失败,系统返回到input对应的页面,要在input对应的页面输出文件过滤失败信息,可以在input对应的页面中增加 <s:fielderror/>来显示错误信息。

运行调试:

结果:

         显然,这样的提示不太友好,应用使用国际化信息。在国际化资源文件中添加如下三句:

              

#更改上传文件类型不允许的提示信息

struts.messages.error.content.type.not.allowed=文件上传失败:你要上传的文件类型不允许

#更改上传文件太大的提示信息

struts.messages.error.file.too.large=文件上传失败:你要上传的文件太大

#文件上传其它错误信息

struts.messages.error.uploading=文件上传失败:发生内部错误

         别忘了要用native2ascii.exe进行编码转换哦。再运行调试:

另外,在控制台会看到一条消息:

              

Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir

Removing file upload D:\tomcat6.0.13\work\Catalina\localhost\fileload_struts2\upload__4b616fd1_115a3d5d9dc__7fff_00000005.tmp

第一个说是找不以struts.multipart.saveDir,即没有指定临时文件夹,这个很好解决,只需指定一个struts.multipart.saveDir常量值为某个目录来解决。第二个说正在删除一个临时文件,这个临时文件是上传过程中产生的,属正常。

4.    多文件上传:

Struts2也可以很方便地实现多文件上传。

         在输入表单域增加多个文件域:multifileupload.jsp

              



<%@ page language="java" contentType="text/html; charset=UTF-8"%>

<%@ taglib uri="/struts-tags" prefix="s" %>

<html>

<head>

    <title>多文件上传</title>

</head>

<body>

    <font color="red"><s:fielderror/></font>

    <form action="multiFileUpload.action" method="POST" enctype="multipart/form-data">

        文件标题:<input type="text" name="title" size="50" value="${param.title }"/><br/>

       <!-- 设置二个文件域,名字相同 -->

        选择第一个文件:<input type="file" name="upload" size="50"/><br/>

        选择第二个文件:<input type="file" name="upload" size="50"/><br/>

       <input type="submit" value=" 上传 "/>      

    </form>

</body>

</html>



         在Action类中用数组来封装该多个文件域:MultiFileUploadAction.java

              



package org.qiujy.web.struts2;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**

*处理多文件上传的Action类

*

*@authorqiujy

*@version1.0

*/

publicclass MultiFileUploadAction extends ActionSupport {

    privatestaticfinalintBUFFER_SIZE = 16 * 1024;

    // 文件标题

    private String title;

    // 用File数组来封装多个上传文件域对象

    private File[] upload;

    // 用String数组来封装多个上传文件名

    private String[] uploadFileName;

    // 用String数组来封装多个上传文件类型

    private String[] uploadContentType;

    // 保存文件的目录路径(通过依赖注入)

    private String savePath;

    //以下为所有属性的getter和setter。省略。。。

    // 自己封装的一个把源文件对象复制成目标文件对象

    privatestaticvoid copy(File src, File dst) {

        InputStream in = null;

        OutputStream out = null;

        try {

            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);

            out = new BufferedOutputStream(new FileOutputStream(dst),

                    BUFFER_SIZE);

            byte[] buffer = newbyte[BUFFER_SIZE];

            int len = 0;

            while ((len = in.read(buffer)) > 0) {

                out.write(buffer, 0, len);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (null != in) {

                try {

                    in.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (null != out) {

                try {

                    out.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    @Override

    public String execute() throws Exception {

        File[] srcFiles = this.getUpload();

        // 处理每个要上传的文件

        for (int i = 0; i < srcFiles.length; i++) {

            // 根据服务器的文件保存地址和原文件名创建目录文件全路径

            String dstPath = ServletActionContext.getServletContext()

                    .getRealPath(this.getSavePath())

                    + "\\" + this.getUploadFileName()[i];

            File dstFile = new File(dstPath);

            this.copy(srcFiles[i], dstFile);

        }

        returnSUCCESS;

    }

}



运行结果:

5.    Struts2的文件下载:

文件下载相对简单一些,一般只需在页面上提供一个超链接,该链接的href属性等于要下载文件的文件名就行了。但当文件名有中文时,就会导致失败;或者要在用户下载前进行权限判断,这时用Struts2提供的文件下载功能就能简单的解决这些问题。


2009-05-25

--------------------------------------------------------------------------------

Love begins with a smile, grows with a kiss, ends with a tear. When you were born, you were crying and everyone around you was smiling. Live your life so that when you die, you're the one smiling and everyone around you is crying.20:47 | 添加评论 | 固定链接 | 写入日志[Struts]转Struts2.0上传文件(1)
Struts2.0上传文件(1)
1.    文件上传的原理:

表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:

1)      application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式。

2)      multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数里。

3)      text/plain:这种方式主要适用于直接通过表单发送邮件的方式。

文件上传是web应用经常用到的一个知识。原理是,通过为表单元素设置enctype="multipart/form-data"属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。

在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件 (http://commons.apache.org/fileupload/),另一个是Oreilly组织的COS框架(http: //www.servlets.com/cos/)。利用这两个框架都能很方便的实现文件的上传。

2.    Struts2的文件上传:

Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form-data的请求,它需要调用其他请求解析器,将HTTP请求中的表单域解析出来。但Struts2在原有的上传解析器基础上做了进一步封装,更进一步简化了文件上传。

Struts2默认使用的是Jakarta的Common-FileUpload框架来上传文件,因此,要在web应用中增加两个Jar文件:commons-fileupload-1.2.jar和commons-io-1.3.1.jar。它在原上传框架上做了进一步封装,简化了文件上传的代码实现,取消了不同上传框架上的编程差异。

如果要改成其它的文件上传框架,可以修改struts.multipart.parser常量的值为cos/pell,默认值是jakata。并在classpath中增加相应上传组件的类库。

2.1.    步骤一:创建带上传表单域的页面               



<%@ page language="java" contentType="text/html; charset=UTF-8"%>

<html>

<head>

    <title>Struts2 File Upload</title>

</head>

<body>

    <form action="fileUpload.action" method="POST" enctype="multipart/form-data">

        文件标题:<input type="text" name="title" size="50"/><br/>

        选择文件:<input type="file" name="upload" size="50"/><br/>

       <input type="submit" value=" 上传 "/>      

    </form>

</body>

</html>



此页面特殊之处只是把表单的enctype属性设置为multipart/form-data。

2.2.    步骤二:创建处理上传请求的Action类

              



package org.qiujy.web.struts2;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**

*处理文件上传的Action类

*@authorqiujy

*@version1.0

*/

publicclass FileUploadAction extends ActionSupport {

    privatestaticfinalintBUFFER_SIZE = 16 * 1024;

    // 文件标题

    private String title;

    // 上传文件域对象

    private File upload;

    // 上传文件名

    private String uploadFileName;

    // 上传文件类型

    private String uploadContentType;

    // 保存文件的目录路径(通过依赖注入)

    private String savePath;

    //以下省略getter和setter......

    //自己封装的一个把源文件对象复制成目标文件对象

    privatestaticvoid copy(File src, File dst) {

        InputStream in = null;

        OutputStream out = null;

        try {

            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);

            out = new BufferedOutputStream(new FileOutputStream(dst),

                    BUFFER_SIZE);

            byte[] buffer = newbyte[BUFFER_SIZE];

            int len = 0;

            while ((len = in.read(buffer)) > 0) {

                out.write(buffer, 0, len);

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (null != in) {

                try {

                    in.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

            if (null != out) {

                try {

                    out.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    @Override

    public String execute() throws Exception {

        //根据服务器的文件保存地址和原文件名创建目录文件全路径

        String dstPath = ServletActionContext.getServletContext()

                                .getRealPath(this.getSavePath())

                                + "\\" + this.getUploadFileName();

      

        System.out.println("上传的文件的类型:"+ this.getUploadContentType());

      

        File dstFile = new File(dstPath);

        copy(this.upload, dstFile);

        returnSUCCESS;

    }

}



上面这个Action类中,提供了title和upload两个属性来分别对应页面的两个表单域属性,用来封装表单域的请求参数。

但是,值得注意的是,此Action中还有两个属性:uploadFileName和uploadContentType,这两个属性分别用于封装上传文件的文件名、文件类型。这是Struts2设计的独到之处:Strut2的Action类直接通过File类型属性直接封装了上传文件的文件内容,但这个File属性无法获取上传文件的文件名和文件类型,所以Struts2就直接将文件域中包含的上传文件名和文件类型的信息封装到 uploadFileName和uploadContentType属性中,也就是说Struts2针对表单中名为xxx的文件域,在对应的Action 类中使用3个属性来封装该文件域信息:

l 类型为File的xxx属性:用来封装页面文件域对应的文件内容。

l 类型为String的xxxFileName属性:用来封装该文件域对应的文件的文件名。

l 类型为String的xxxContentType属性:用来封装该文件域应用的文件的文件类型。

另外,在这个Action类中还有一个savePath属性,它的值是通过配置文件来动态设置的,这也是Strut2设计中的一个依赖注入特性的使用。

2.3.    步骤三:配置

struts.xml文件:



               

<!DOCTYPE struts PUBLIC

        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"

        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <package name ="fileUploadDemo" extends ="struts-default">

        <action name ="fileUpload"

class ="org.qiujy.web.struts2.FileUploadAction">

<!-- 动态设置Action中的savePath属性的值 -->

            <param name="savePath">/upload</param>

            <result name ="success">/showupload.jsp</result>

        </action >

    </package >

</struts>




2009-05-25

--------------------------------------------------------------------------------

Love begins with a smile, grows with a kiss, ends with a tear. When you were born, you were crying and everyone around you was smiling. Live your life so that when you die, you're the one smiling and everyone around you is crying.20:47 | 添加评论 | 固定链接 | 写入日志[Struts]Struts1.2 处理上传文件
Struts1.2 处理上传文件



1.上传文件的jsp文件代码



<%@ page contentType="text/html;charset=GBK" language="java" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>



<html>

<head>

<title>一个上传文件的例子</title>

</head>

<BODY>

<h1>一个上传文件的例子</h1>

<html:errors/><br>

<html:form action="uploadfile.do" enctype="multipart/form-data">

    <html:file property="file" /><br><br>

    <html:submit></html:submit>

</html:form>

</BODY>

</html>







2.ActionForm类代码



public class UploadFileForm extends ActionForm {



private FormFile file=null;

//private String fname;

//private String size;

//private String url;



public FormFile getFile(){

    return file;

}

public void setFile(FormFile file){

    this.file=file;

}

//**************验证文件如果为空则返回*****************

public ActionErrors validate(

    ActionMapping mapping,

    HttpServletRequest request) {

 

    ActionErrors errors=new ActionErrors();

 

    if(file==null || file.getFileSize()<5 || file.getFileName()==null){

     errors.add("file",new ActionError("error.file.null"));

    }

 

    return errors;

}





}



3.Action类的代码



public class UploadFileAction extends Action{





public ActionForward execute (

    ActionMapping mapping,

    ActionForm form,

    HttpServletRequest request,

    HttpServletResponse response) throws Exception{

 

    ActionErrors errors=new ActionErrors(); 

 

    UploadFileForm hff=(UploadFileForm)form; 

    FormFile file=hff.getFile();

 

 

    //*************如果ActionForm中没验证则加上这段*****************

    //if(file==null || file.getFileSize()<10 || file.getFileName()==null){

    // errors.add("file",new ActionError("error.file.null"));

    // saveErrors(request,errors);

    // return (new ActionForward(mapping.getInput()));

    //}

 

          //*************取得上传文件的信息****************

    String dir=servlet.getServletContext().getRealPath("/upload");

    String fname=file.getFileName();

    String size=Integer.toString(file.getFileSize())+"bytes";

    String url=dir+"\\"+fname;

 

    //*************限制非图片文件的上传*******************

    String fileType=(fname.substring(fname.lastIndexOf('.')+1)).toLowerCase();

    if((!fileType.equals("jpg")) && (!fileType.equals("bmp")) && (!fileType.equals("gif")) && (!fileType.equals("jpeg"))){

     errors.add("filetype",new ActionError("error.file.type"));

     saveErrors(request,errors);

     return (new ActionForward(mapping.getInput()));

    }

 

    //*************限制文件不能超过2M******************

    if(file.getFileSize()>2097152){

     errors.add("size",new ActionError("error.file.size"));

     saveErrors(request,errors);

     return (new ActionForward(mapping.getInput()));

    } 

  

    //*************要用到的输入输出流*****************

    InputStream streamIn=file.getInputStream();

    OutputStream streamOut=new FileOutputStream(url);

 

    //*************将文件输出到目标文件*****************

    int bytesRead=0;

    byte[] buffer=new byte[8192];

    while((bytesRead=streamIn.read(buffer,0,8192))!=-1){

     streamOut.write(buffer,0,bytesRead);

    }

 

    streamOut.close();

    streamIn.close();

    file.destroy();   

   

    return mapping.findForward("sucess");

}



}




2009-05-25

--------------------------------------------------------------------------------

Love begins with a smile, grows with a kiss, ends with a tear. When you were born, you were crying and everyone around you was smiling. Live your life so that when you die, you're the one smiling and everyone around you is crying.20:44 | 添加评论 | 固定链接 | 写入日志[jsp]转:FCKeditor2.6,FCKeditor2.4 for java
FCKeditor2.6,FCKeditor2.4 for java
FCKeditor2.6,FCKeditor2.4 for java 最经典的配置说明,转:http://hi.baidu.com/chendychendy/blog/item/b2fa06c3f758a9130ef477da.html
JSP中FCKeditor2.6设置For2.4上传驱动包
FCKEDITOR 2.6.4正式版本已经发布
http://www.fckeditor.net/
--------
著名WEB文本编辑器开发社区FCKeditor在官方网站www.fckeditor.net推出Fckeditor 2.6.xBeta版本,官方消息称在8月初将发布其正式稳定版本,另人期待:)
在http://www.fckeditor.net/whatsnew可一看到每个版本所做的改动
FCKeditor得到了越来越多人的支持,轻量级的FCKeditor被众多网站所使用,希望能做的更好.
话不多说,接下来我们如何用FCKeditor 2.6加上Java Fckeditor运行包2.4版本来构建一个能正常上传文件的WEB文本编辑器.在最后附上我的测试Demo给大家
1,准备:
测试服务器resin 3.0.x,JDK 1.6 ,XPSP2系统
FCKeditor 2.6 公用文件:
下载:
http://www.fckeditor.net/whatsnew
FCKeditor 2.4 Java 上传驱动包
先申明一下,FCKeditor 2.4 Java比以前的2.3 java上传驱动更好设置,上传功能也实现的比以前的要完美.
但还需要以下4个组件包:
slf4j-api-1.5.2.jar
slf4j-jdk14-1.5.2.jar[?在fckeditor-java-2.4.1-bin.zip 中的lib中并没有这个包,同时没有这个包也可以进行文件上传,测试日期09/05/25]
地址:http://www.slf4j.org/download.html
slf4j下载后解压只选择里面的以上两个包即可.
commons-io-1.4.jar
地址:http://commons.apache.org/io/
commons-fileupload-1.2.1.jar
地址:http://commons.apache.org/fileupload/
FCKeditor 2.4 Java下载:
http://www.fckeditor.net/download
FCKeditor 里面附带web.xml [**++**现在 fckeditor-java-2.4.1-bin.zip 中并没有 web.xml了, 但可以下一个 实例包fckeditor-java-demo-2.4.1.war,这个里面有, 同时也有properties资源文件,这些文件我们可以用来做修改的参考以便加快我们的配置]
将准备的jar java包放到我们的测试工程目录WEB-INF/lib下
把FCKeditor 2.4 Java解压出来的web.xml放到WEB-INF/下及FCKeditor2.4.jar放到lib下
并把web.xml里的
<web-app version="2.4" id="fckeditor-java" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>
<display-name>FCKeditor.Java Sample Web Application</display-name>
修改为
<web-app xmlns="http://caucho.com/ns/resin" xmlns:resin="http://caucho.com/ns/resin/core">
<display-name>www.txdnet.cn</display-name>
resin的web-app信息
工程目录即为ROOT根目录,方便测试.
在WEB-INF/classes里建立如下资源文件:
#**---------下面的资料文件配置非常经典----------------***************
fckeditor.properties
fckeditor的信息即在这个文件里设置.
文件参数:
connector.userFilesPath=/UserUploadFile
connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl
###此处不写入资源文件则默认放在userFilesPath目录下###
#connector.resourceType.file.path
#connector.resourceType.image.path
#connector.resourceType.flash.path
#connector.resourceType.media.path
###########################################
connector.resourceType.file.extensions.allowed=|jpg|gif|png|rar|zip|txt|doc|wma|wmv|mp3|flv|swf|
connector.resourceType.file.extensions.denied=|com|exe|jsp|html|htm|shtml|bat|
connector.resourceType.media.extensions.allowed=|wma|wmv|mp3|flv|swf|
connector.resourceType.media.extensions.denied=|com|exe|jsp|html|htm|shtml|bat|
connector.resourceType.image.extensions.allowed=|jpg|png|gif|
connector.resourceType.image.extensions.denied=|com|exe|jsp|html|htm|shtml|bat|
connector.resourceType.flash.extensions.allowed=|swf|
connector.resourceType.flash.extensions.denied=|com|exe|jsp|html|htm|shtml|bat|
将Fckeditor 2.6公用文件解压放到ROOT下
大体的文件目录位置如下:
ROOT
|
|-WEB-INF/
| |-lib...(5个jar包)
| |-classes...(一个资源文件)
| |-web.xml
|-fckeditor/...(目录下有fckeditor.js,editor文件夹)
|-index.jsp(测试fckeditor文件)
|-GetData.jsp(得到提交信息并显示)
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>
</servlet-mapping>
2,测试
文件index.jsp;GetData.jsp代码(用EditPlus编辑保存为UTF-8):
**************************************index.jsp代码
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page contentType="text/html; charset=UTF-8"
language="java"
import="java.io.*,java.net.*"
buffer="32kb"
autoFlush="true" %>
<%@ page pageEncoding="UTF-8" %>
<!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" />
<title></title>
<script type="text/javascript" src="fckeditor/fckeditor.js"></script>
<style type="text/css">
<!--
body{ font-family:Verdana,Arial,Helvetica,sans-serif;font-size:13px}
#Layer1{position:absolute;left:18px;top:5px;;height:500px;z-index:1}
#Content{;height:420px}
-->
</style>
<%@ taglib uri="http://java.fckeditor.net" prefix="FCK"%><!--本人另外添加,FCK的另一种配置方法,使用FCK标签进行配置-->
</head>
<body>
<form id="FCKForm" name="FCKForm" ACTION="GetData.jsp" METHOD="POST">
<script type="text/javascript" language="javascript">
var oFCKeditor = new FCKeditor('editor') ;
oFCKeditor.BasePath ='/fckeditor/';
oFCKeditor.ToolbarSet ='Default';
oFCKeditor.Value ='测试Fckeditor';
oFCKeditor.Create() ;
</script>
<INPUT TYPE="submit">
</form>
<!--本人另外添加,FCK的另一种配置方法,使用FCK标签进行配置-->
<form action="GetData.jsp" method="post" id="FCKForm2" name="FCKForm2">
     <FCK:editor  instanceName="editor"  value="default content" ></FCK:editor>
    </form>
</body></html>
******************************GetData.jsp代码
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java"
contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"
import="java.util.Enumeration;"%>
<!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>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<%
Enumeration&lt;String> params = (Enumeration<String>) request.getParameterNames();
%&gt;
<body>
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr />
<table ;100%" border="1" cellspacing="0">
<tr style="FONT-WEIGHT: bold; COLOR: #dddddd; BACKGROUND-COLOR: #999999">
<td nowrap="nowrap">Field Name&nbsp;&nbsp;</td>
<td>Value</td>
</tr>
<%
String parameter;
while(params.hasMoreElements()) {
parameter = params.nextElement();
%>
<tr>
<td nowrap="nowrap"><b><%=parameter%></b></td>
<td ;100%"><%=request.getParameter(parameter)%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
3,运行测试
上传一切OK
4,小技巧:
1)上传文件名自动变成日期数字格式如20080727185907500.gif/.rar/.doc/.gif等等
在下载的FCKEditor 2.4 For Java中解压得到原码
找到这个Java Class原文件
ConnectorServlet.java
在Class中import以下外部类
import java.text.*;
import java.util.*;
在Class中增加一个方法
//Edit By Txdnet.Cn
public static final String getStrDate(int int_dateFormat )
{
String[] dateFormat = {
"yyyyMMddHHmmssSSS",
"yyyyMMddHHmmss",
"yyMMddHHmmss",
"yyyyMMdd",
"yyyy-MM-dd",
"HHmmssSSS",
"HHmmss"
};
SimpleDateFormat sdf = null;
try{
sdf = new SimpleDateFormat(dateFormat[int_dateFormat]);
}
catch(Exception ex)
{
ex.printStackTrace();
System.out.print(ex.toString());
return ex.toString();
}
return sdf.format(new Date());
}
//End Edit
将POST处理方法中的
String baseName =FilenameUtils.removeExtension(filename);
改为
String baseName =getDate(0); //FilenameUtils.removeExtension(filename);
并在
String extension = FilenameUtils.getExtension( filename );
下行增加
//Edit By TXDNET.CN
filename = baseName.concat(".").concat( extension.toLowerCase() );
//END Edit
重新编译打包成FCKeditor2.4ByTxdnet.jar
覆盖lib原来的FCKeditor2.4.jar
2)限制上传文件的权限,FCKEditor 2.4 For Java提供了相应的UserAction接口,可以实现一个类来控制权限.
Java代码
package com.tail.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import net.fckeditor.requestcycle.UserAction;
import com.tail.beans.Principal;
import com.tail.objects.User;
public class UserActionImpl implements UserAction {
public boolean isEnabledForFileBrowsing(HttpServletRequest req) {
return true;
}
public boolean isEnabledForFileUpload(HttpServletRequest req) {
HttpSession session = req.getSession();
Principal principal = (Principal) session.getAttribute(ConstantUtil.SESSION_PRINCIPAL);
if (principal != null) {
User user = principal.getUser();
if (user.isUploadable()) {
return true;
}
}
return false;
}
}
如何加载自定义的UserAction类呢?在classes的根目录下,你需要在fckeditor.properties文件中定义:
connector.userActionImpl=com.tail.utils.UserActionImpl
这样就可以控制文件上传权限.
5,总结.
FCKeditor 2.4可以说是一个小的飞跃,改变了以往在web.xml中让很多人迷糊的设置,对上传处理可以做到令人满意的效果,故写了这篇文章与大家分享.
问题:
中文文件上传仍然是个问题,但以往个人在设计上传类时却没有碰到这个问题,推测原因是:虽然FCKeditor包括For java包类都做到统一编码,但忽略了一点,编写的java类源文件仍然是系统默认的,是随系统改变的,据个人的经验,如果编写的java原文件通过 EditPlus(或其他能很好处理编码的文本编辑器)另存为utf-8格式的java文件 再加入javac -encoding utf-8编译指令手动生成class,在加上一些统一编码的措施(过滤器,String转码)就能够保存中文名文件和读取有中文名的文件和目录,期待以后的版本能够解决.
在上传文件目录的设置上存在疑问,如果fckeditor及调用的jsp不在ROOT下呢?或其他目录的使用上,个人没做过更多的测试,Happy漫步者在此还望大家多多交流经验:)
FCKeditor2.6,FCKeditor2.4 for java 最经典的配置说明,转:http://hi.baidu.com/chendychendy/blog/item/b2fa06c3f758a9130ef477da.html
分享到:
评论

相关推荐

    FCKeditor2.6 在线文本编辑器例子

    FCKeditor是一个非常强大的在线文本编辑器,而且还是开源的。支持多种浏览器,而且被国内诸多博客使用。 本例采用FCKeditor2.6+FCKeditor for Java Driver2.41 最新配置例子,可以处理中文乱码、限制上传的文件的大小。

    FCKeditor2.6 在线编辑器

    FCKeditor是一款功能强大的开源在线文本编辑器(DHTML editor),它使你在web上可以使用类似微软Word 的桌面文本编辑器的许多强大功能

    FCKeditor 2.6 在线编辑器

    开源的HTML文本编辑器可以让Web程序拥有如MS Word这样强大的编辑功能.经过本人测试修改,完整无错。内附实例。

    最新FCKeditor_2.6 版本 FCKeditor编辑器和控件

    兼容目前的浏览器 里面包含FCKeditor编辑器和控件 一、集成方法 FCKeditor应用在ASP.NET上,需要两组文件,一组是FCKeditor本身,另一个是用于ASP.NET的FCKeditor控件(分为1.1和2.0两个版本,这里使用2.0版本)。 ...

    FCKeditor2.6 for asp.net

    针对asp.net的FCKeditor2.6编辑器 花了一天的时间才弄好的 精简版的 可以直接使用

    FCKeditor_2.6.4.1

    好用的文本编辑器fckeditor好用的文本编辑器好用的文本编辑器好用的文本编辑器

    FCKeditor_2.6.6+FCKeditor.Net_2.6.4

    FCKeditor_2.6.6 + FCKeditor.Net_2.6.4 ,ASP.NET下用的文本编辑器。

    FCKeditor v2.6 精简第三版

    FCKeditor是一款功能强大的开源在线文本编辑器(DHTML editor),它使你在web上可以使用类似微软Word 的桌面文本编辑器的许多强大功能。它是轻量级且不必在客户端进行任何方式的安装。FCKeditor兼容 Firefox, Mozilla,...

    网页编辑器fckeidtor2.6

    已经试用过,完全没问题,希望能帮倒你们,注:在JSP或html里用javascipt引入,引入语句为[removed][removed], 在URL上输入http://localhost:8080/项目名/fckeditor/_samples/default.html...有输出编辑器表示载入成功

    FCKeditor_2.6.8.zip

    很不错的资源,在先编辑器,可以编辑图文混合的文本

    JAVA WEB典型模块与项目实战大全

    4.2 fckeditor在线文本编辑器初级应用  4.3 fckeditor在线文本编辑器常用配置  4.4 fckeditor在线文本编辑器高级应用  4.5 小结  第5章 验证模块(jsp+servlet+jsvaildation)  5.1 表单基础  5.2 客户端...

    fckconfig.js中文注释

    //开启时焦点是否到编辑器,即打开页面时光标是否停留在fckeditor上 26. FCKConfig.ForcePasteAsPlainText = false ; //是否强制粘贴为纯文件内容 27. FCKConfig.AutoDetectPasteFromWord = true ; //是否自动探测...

    ECSHOP设置及开发技巧汇总

    2.20 分类描述使用FCKeditor作为编辑器 56 2.21 如何去掉ECSHOP帮助中心文章页的评论功能 57 2.22 ecshop 自定义分类模板的方法 59 2.23 多语言 62 2.24 实现自动选择语言转跳转 65 2.25 ecshop模板中如何调程序 66 ...

Global site tag (gtag.js) - Google Analytics