修正Strut2 自带上传拦截器功能

原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 、作者信息和本声明。否则将追究法律责任。http://dba10g.blog.51cto.com/764602/857866

Struts2字典的FileUploadInterceptor 拦截器 主要帮助获取上传文件的ContentType、fileName、文件对象。如果开发人员在开发过程中使用。则需要设置set/get方法:

比如

setXXXContentType() 
getXXXFileName() 
getXXXContentType() 
setXXXFileName() 
getXXXFile() 
setXXXFile()

其中,"xxx"为渲染器的name.

 

问题在这里

第一,如果除了ContentType/File/FileName ,还需要其他的消息怎么办呢。拦截器就无能为力了。 这个可以忽略。

 

第二,平时在开发过程中,我们经常有动态添加附件功能。如果上传的附件同属于一类的话,还尚可。但是,如果一个页面中,需要上传多种类型的附件,而且每个附件类型动态增加的。拦截器就有点力不从心了。只能针对每个类型的附件,在Action中写多个方法。

setType1File();

setType2File();

setType1ContentType();

setType2ContentType();

setType1FileName();

setType2FileName();

---------

问题在这里。如果我再增加一个类型呢?

在深层挖掘一下,如果我想做一个公共的文件上传处理类,怎么办。

本人研究了下自带的拦截器,在此基础上,通过自己的实践,提出自己的一个解决方案。

 

我通过Map 来管理上传的文件列表。这样就不惧怕多类型文件上传,且可扩展性也提高了。

修正后的Strut2 FileUploadInterceptor 如下

public String intercept(ActionInvocation invocation) throws Exception { 
                ActionContext ac = invocation.getInvocationContext(); 

                HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); 

                if (!(request instanceof MultiPartRequestWrapper)) { 
                        if (LOG.isDebugEnabled()) { 
                                ActionProxy proxy = invocation.getProxy(); 
                                LOG.debug(getTextMessage("struts.messages.bypass.request", new Object[]{proxy.getNamespace(), proxy.getActionName()}, ac.getLocale())); 
                        } 

                        return invocation.invoke(); 
                } 

                ValidationAware validation = null; 

                Object action = invocation.getAction(); 

                if (action instanceof ValidationAware) { 
                        validation = (ValidationAware) action; 
                } 

                MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request; 

                if (multiWrapper.hasErrors()) { 
                        for (String error : multiWrapper.getErrors()) { 
                                if (validation != null) { 
                                        validation.addActionError(error); 
                                } 

                                LOG.warn(error); 
                        } 
                } 

                // bind allowed Files 
                Enumeration fileParameterNames = multiWrapper.getFileParameterNames(); 
                Map<String,List<Map<String,Object>>> fileParameterMap = new HashMap<String,List<Map<String,Object>>>();//文件值对 //zhaogy 
                while (fileParameterNames != null && fileParameterNames.hasMoreElements()) { 
                        // get the value of this input tag 
                        String inputName = (String) fileParameterNames.nextElement(); 
                         
                        // get the content type 
                        String[] contentType = multiWrapper.getContentTypes(inputName); 
                         
                        if (isNonEmpty(contentType)) { 
                                // get the name of the file from the input tag 
                                String[] fileName = multiWrapper.getFileNames(inputName); 

                                if (isNonEmpty(fileName)) { 
                                        // get a File object for the uploaded File 
                                        File[] files = multiWrapper.getFiles(inputName); 
                                        if (files != null && files.length > 0) { 
                                                List<File> acceptedFiles = new ArrayList<File>(files.length); 
                                                List<String> acceptedContentTypes = new ArrayList<String>(files.length); 
                                                List<String> acceptedFileNames = new ArrayList<String>(files.length); 
                                                List<String> renderNames = new ArrayList<String>(files.length); 
                                                String contentTypeName = inputName + "ContentType"; 
                                                String fileNameName = inputName + "FileName"; 
                                                for (int index = 0; index < files.length; index++) { 
                                                        if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) { 
                                                                acceptedFiles.add(files[index]); 
                                                                acceptedContentTypes.add(contentType[index]); 
                                                                acceptedFileNames.add(fileName[index]); 
                                                                List<Map<String, Object>> vfl=null; 
                                                                if(fileParameterMap.containsKey(inputName)){//是否已存在
                                                                  vfl = fileParameterMap.get(inputName); 
                                                                }else{ 
                                                                  vfl = new ArrayList<Map<String,Object>>(); 
                                                                  fileParameterMap.put(inputName, vfl); 
                                                                } 
                                                                  Map<String, Object> value = new HashMap<String,Object>(); 
                                                                  value.put("contentType", contentType[index]); 
                                                                  value.put("fileName", fileName[index]); 
                                                                  value.put("acceptedFile", files[index]); 
                  vfl.add(value); 
                                                                 
                                                        } 
                                                } 

                                                if (!acceptedFiles.isEmpty()) { 
                                                        Map<String, Object> params = ac.getParameters(); 
                                                        params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()])); 
                                                        params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()])); 
                                                        params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()])); 
                                                        params.put("fileParameterMap", fileParameterMap);// zhaogy 
                                                } 
                                        } 
                                } else { 
                                        LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new Object[]{inputName}, ac.getLocale())); 
                                } 
                        } else { 
                                LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new Object[]{inputName}, ac.getLocale())); 
                        } 
                } 

                // invoke action 
                String result = invocation.invoke(); 

                // cleanup 
                fileParameterNames = multiWrapper.getFileParameterNames(); 
                while (fileParameterNames != null && fileParameterNames.hasMoreElements()) { 
                        String inputValue = (String) fileParameterNames.nextElement(); 
                        File[] files = multiWrapper.getFiles(inputValue); 

                        for (File currentFile : files) { 
                                if (LOG.isInfoEnabled()) { 
                                        LOG.info(getTextMessage(action, "struts.messages.removing.file", new Object[]{inputValue, currentFile}, ac.getLocale())); 
                                } 

                                if ((currentFile != null) && currentFile.isFile()) { 
                                        if (currentFile.delete() == false) { 
                                                LOG.warn("Resource Leaking:    Could not remove uploaded file '" + currentFile.getCanonicalPath() + "'."); 
                                        } 
                                } 
                        } 
                } 

                return result; 
        }

 

 

 

测试代码:

/* 
* $Id: MultipleFileUploadUsingListAction.java 660522 2008-05-27 14:08:00Z jholmes $ 

* Licensed to the Apache Software Foundation (ASF) under one 
* or more contributor license agreements.    See the NOTICE file 
* distributed with this work for additional information 
* regarding copyright ownership.    The ASF licenses this file 
* to you under the Apache License, Version 2.0 (the 
* "License"); you may not use this file except in compliance 
* with the License.    You may obtain a copy of the License at 

*    http://www.apache.org/licenses/LICENSE-2.0 

* Unless required by applicable law or agreed to in writing, 
* software distributed under the License is distributed on an 
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
* KIND, either express or implied.    See the License for the 
* specific language governing permissions and limitations 
* under the License. 
*/ 
// START SNIPPET: entire-file 
package org.apache.struts2.showcase.fileupload; 
import java.io.File; 
import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 

import com.opensymphony.xwork2.ActionSupport; 

/** 
* Showcase action - multiple file upload using List 
* @version $Date: 2008-05-27 16:08:00 +0200 (Tue, 27 May 2008) $ $Id: MultipleFileUploadUsingListAction.java 660522 2008-05-27 14:08:00Z jholmes $ 
*/ 
public class MultipleFileUploadUsingListAction extends ActionSupport { 

        private List<File> uploads = new ArrayList<File>(); 
        private List<String> uploadFileNames = new ArrayList<String>(); 
        private List<String> uploadContentTypes = new ArrayList<String>(); 

  public void setFileParameterMap( 
      Map<String, List<Map<String, Object>>> fileParameterMap) { 
    this.fileParameterMap = fileParameterMap; 
  } 
  public List<File> getUpload() { 
                return this.uploads; 
        } 
        public void setUpload(List<File> uploads) { 
                this.uploads = uploads; 
        } 

        public List<String> getUploadFileName() { 
                return this.uploadFileNames; 
        } 
         
         
        public void setUploadFileName(List<String> uploadFileNames) { 
                this.uploadFileNames = uploadFileNames; 
        } 

        public List<String> getUploadContentType() { 
                return this.uploadContentTypes; 
        } 
        public void setUploadContentType(List<String> contentTypes) { 
                this.uploadContentTypes = contentTypes; 
        } 
        private Map<String,List<Map<String,Object>>> fileParameterMap; 

        public Map<String, List<Map<String, Object>>> getFileParameterMap() { 
    return fileParameterMap; 
  } 
         
        public String upload() throws Exception { 
          Iterator<String> iter = this.fileParameterMap.keySet().iterator(); 
    while(iter.hasNext()){ 
             String key = iter.next(); 
             List<Map<String, Object>>    vs = this.fileParameterMap.get(key); 
             System.out.println("key========"+key); 
             for(Map<String, Object> v : vs){ 
                Object contentType = v.get("contentType"); 
                Object fileName = v.get("fileName"); 
              Object file =    v.get("acceptedFile"); 
              System.out.println("contentType>>"+contentType); 
              System.out.println("fileName>>"+fileName); 
              System.out.println("file>>"+file); 
             } 
          } 
//                System.out.println("\n\n upload1"); 
//                System.out.println("files:"); 
//                for (File u: uploads) { 
//                        System.out.println("*** "+u+"\t"+u.length()); 
//                } 
//                System.out.println("filenames:"); 
//                for (String n: uploadFileNames) { 
//                        System.out.println("*** "+n); 
//                } 
//                System.out.println("content types:"); 
//                for (String c: uploadContentTypes) { 
//                        System.out.println("*** "+c); 
//                } 
//                System.out.println("\n\n"); 
                return SUCCESS; 
        } 

// END SNIPPET: entire-file

 

输出

key========upload2
contentType>>application/octet-stream
fileName>>xm_xvs.cfg
file>>D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000011.tmp
contentType>>text/html
fileName>>login.html
file>>D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000012.tmp
key========upload
contentType>>text/plain
fileName>>说明.txt
file>>D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000008.tmp
contentType>>application/vnd.openxmlformats-officedocument.wordprocessingml.document
fileName>>孕妇饮食注意事项.docx
file>>D:\Tomcat-6.0.20\work\Catalina\localhost\struts2-showcase\upload_8c1aaae_1372ca9bef5__8000_00000009.tmp

 

 

本文出自 “简单” 博客,请务必保留此出处http://dba10g.blog.51cto.com/764602/857866

时间: 2024-09-18 03:37:27

修正Strut2 自带上传拦截器功能的相关文章

struts2中文件上传拦截器 是不是不能在多个action中引用???

问题描述 <global-results> <result name="input">/message.jsp</result></global-results><!--定义全局的返回视图--><action name="updateHead" class="updateHead"> <interceptor-ref name="fileUpload"

struts2 配置的文件上传拦截器没有生效

问题描述 struts2配置了文件上传拦截器只允许上传图片,为什么没有生效的呢?其他类型文件还是能够上传 解决方案 解决方案二:但其他文件上传后台会报错,其实没传成功的吧这个要上传前端控制下吧

js HTML5 Ajax实现文件上传进度条功能_javascript技巧

本文实例介绍了js结合HTML5 Ajax实现文件上传进度条功能,分享给大家供大家参考,具体内容如下 1.  lib.js var Host = window.location.host; //--Cookie function setCookie(name,value) { var Days = 30; var exp = new Date(); exp.setTime(exp.getTime() + Days*24*60*60*1000); document.cookie = name +

安卓文件上传下载-我是安卓开发学了一点,大家可以给我讲讲如何写一个上传下载的功能

问题描述 我是安卓开发学了一点,大家可以给我讲讲如何写一个上传下载的功能 安卓我是0基础,现在我们老师命令我写一个文件上传下载,可是我只看了那么一点,大家可以给我讲讲思路,自己实际案例 解决方案 首先看看你们老师的要求是上传下载到哪里?然后再搜索方法案例,因为数据存储有多种方式都不一样的 解决方案二: http://download.csdn.net/detail/airlke/8172213

有谁会改FreeTextBox 3.1.6,给控件加插入上传Flash/视频功能?

问题描述 有谁会改FreeTextBox3.1.6,给控件加插入上传Flash/视频功能?小弟给你们跪下了,有的话给我个.....很急哦 解决方案 解决方案二:lollollol解决方案三:接分先!解决方案四:有问题请先GOOGLE,BAIDU

MyBatis与SpringMVC相结合实现文件上传、下载功能_java

环境:maven+SpringMVC + Spring + MyBatis + MySql 本文主要说明如何使用input上传文件到服务器指定目录,或保存到数据库中:如何从数据库下载文件,和显示图像文件并实现缩放. 将文件存储在数据库中,一般是存文件的byte数组,对应的数据库数据类型为blob. 首先要创建数据库,此处使用MySql数据库. 注意:文中给出的代码多为节选重要片段,并不齐全. 1. 前期准备 使用maven创建一个springMVC+spring+mybatis+mysql的项目

php使用APC实现实时上传进度条功能_php技巧

php不具备实时上传进度条功能,如果想有这种功能我们一般会使用ajax来实现,但是php提供了一个apc,它就可以与php配置实现上传进度条功能. 主要针对的是window上的应用.1.服务器要支持apc扩展,没有此扩展的话,下载一个扩展扩展要求php.5.2以上. 2.配置apc相关配置,重启apache代码如下 extension=php_apc.dll   apc.rfc1867 = on   apc.max_file_size = 1000M   upload_max_filesize

Java实现FTP文件的上传和下载功能的实例代码_java

FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为"文传协议".用于Internet上的控制文件的双向传输.同时,它也是一个应用程序(Application).基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件.在FTP的使用当中,用户经常遇到两个概念:"下载"(Download)和"上传"(Upload)."下载"文件就是从远程主机拷贝文件至自己

PHP中使用Session配合Javascript实现文件上传进度条功能_php技巧

Web应用中常需要提供文件上传的功能.典型的场景包括用户头像上传.相册图片上传等.当需要上传的文件比较大的时候,提供一个显示上传进度的进度条就很有必要了. 在PHP 5.4以前,实现这样的进度条并不容易,主要有三种方法: 1.使用Flash, Java, ActiveX 2.使用PHP的APC扩展 3.使用HTML5的File API 第一种方法依赖第三方的浏览器插件,通用性不足,且易带来安全隐患.不过由于Flash的使用比较广泛,因此还是有很多网站使用Flash作为解决方案. 第二种方法的不足