JavaScud | Forum | JIRA | Blog |
  Dashboard > WebWork2文档中文化计划 > ... > Interceptors > File Upload Interceptor
  WebWork2文档中文化计划 Log In View a printable version of the current page.  
  File Upload Interceptor
Added by scud, last edited by scud on Apr 16, 2006  (view change)
Labels: 
(None)

这个拦截器基于MultiPartRequestWrapper,它可以应用于任何一个包含文件的请求. 它提供以下参数, 其中的[File Name]是被HTML表单中上传的文件的名字

  • [File Name] : File - 实际的文件
  • [File Name]ContentType : String - 文件的ContentType
  • [File Name]FileName : String - 上传文件的实际名字(不是HMTL标签的名字)

你只要在你的action中提供任何一种上面形式的set方法就可以访问到这些文件.例如setDocument(得到Document文件),setDocumentContentType(String类型的contentType),等等.

如果你的action实现了ValidationAware接口,这个拦截器就可以添加几种字段错误.这些错误信息是基于存储在webwork-messages.properties文件中的一些i18n值,这个文件是所有i18n请求的默认文件.你可以在自己消息文件的复写以下key的消息文字:

  • webwork.messages.error.uploading - 文件不能上传的通用错误信息
  • webwork.messages.error.file.too.large - 上传文件长度过大的错误信息
  • webwork.messages.error.content.type.not.allowed - 当上传文件不符合指定的contentType

参数

  • maximumSize (可选) - 这个拦截器允许的上传到action中的文件最大长度(以byte为单位). 注意这个参数和在webwork.properties中定义的属性没有关系,默认2MB
  • allowedTypes (可选) - 以逗号分割的contentType类型列表(例如text/html),这些列表是这个拦截器允许的可以传到action中的contentType.如果没有指定就是允许任何上传类型.

扩展

你可以扩展这个拦截器并复写acceptFile方法来实现更好的控制什么文件是被支持的什么是不被支持.

例子

<action name="doUpload" class="com.examples.UploadAction">
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="basicStack"/>
    <result name="success">good_result.ftl</result>
</action>

然后你需要设置上传文件中的表单中的encoding属性为multipart/form-data

<ww:form action="doUpload" method="post" enctype="multipart/form-data">
      <ww:file name="upload" label="File"/>
      <ww:submit/>
</ww:form>

然后在action中代码中加入set方法,你可以访问到File对象了.

public com.examples.UploadAction implemements Action {
      private File file;
      private String contentType;
      private String filename;

      public void setUpload(File file) {
         this.file = file;
      }

      public void setUploadContentType(String contentType) {
         this.contentType = contentType;
      }

      public void setUploadFileName(String filename) {
         this.filename = filename;
      }

      ...

设置参数的例子

<interceptor-ref name="fileUpload">
  <param name="allowedTypes">
     image/png,image/gif,image/jpeg
  </param>
</interceptor-ref>

自己定义的webwork-messages_zh_CN.properties必须也按照webwork的目录结构存放

Posted by Anonymous at Apr 15, 2008 13:15 | Reply To This

为什么不把 完整的例子弄上去

Posted by Anonymous at May 09, 2008 12:33 | Reply To This
Site running on a free Atlassian Confluence Open Source Project License granted to WebWork China. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.3 Build:#808 May 29, 2007) - Bug/feature request - Contact Administrators