struts 多文件上传 annotation注解(零配置)+ ajaxfileupload + 异步 版本

【本文简介】

struts 多文件上传。基于”零配置“+"ajaxfileupload" 的一个简单例子。

【导入依赖jar包】

  1. jquery-1.7.2.js : http://jquery.com/download/
  2. ajaxfileupload.js:http://fileuploadajax.codeplex.com/releases/view/8061

【修改 ajaxfileupload.js 使其支持多文件】

打开js,找到:

1 var oldElement = jQuery('#' + fileElementId);
2 var newElement = jQuery(oldElement).clone();
3 jQuery(oldElement).attr('id', fileId);
4 jQuery(oldElement).before(newElement);
5 jQuery(oldElement).appendTo(form);

改成:

1 for(var i in fileElementId){  
2   var oldElement = jQuery('#' + fileElementId[i]);  
3   var newElement = jQuery(oldElement).clone();  
4   jQuery(oldElement).attr('id', fileId);  
5   jQuery(oldElement).before(newElement);  
6   jQuery(oldElement).appendTo(form);  
7 }

【文件夹结构】

【web.xml】

 1     <filter>
 2         <filter-name>struts2</filter-name>
 3         <filter-class>
 4             org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 5     </filter>
 6     <filter-mapping>
 7         <filter-name>struts2</filter-name>
 8         <url-pattern>*.action</url-pattern>
 9     </filter-mapping>
10     <filter-mapping>
11         <filter-name>struts2</filter-name>
12         <url-pattern>*.jsp</url-pattern>
13     </filter-mapping>

【struts.xml】

 1 <!-- URL资源分隔符 -->
 2     <constant name="struts.convention.action.name.separator" value="_" />
 3     <!-- ****************************以下是文件上传的设置*********************************** -->
 4     <!-- 指定国际化资源文件的baseName为messageResource -->
 5     <!-- 设置该应用使用的解码集 -->
 6     <constant name="struts.i18n.encoding" value="utf-8"/>
 7     <!-- 上传的全部文件的最大限制-->
 8     <constant name="struts.multipart.maxSize" value="1024102400"/>
 9     <!-- 设置存放临时文件的文件夹 -->
10     <constant name="struts.multipart.saveDir" value="/tmp"></constant>
11     <!-- ****************************以上是文件上传的设置*********************************** -->

【JSP代码】

以上的web.xml配置导致下面的访问地址的方法名有要加:.action

以上的struts.xml配置 URL 资源分隔符导致下面的访问地址的 类名第一个字母的大写换成 ”_小写“

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
     
    <title>My JSP 'MyJsp.jsp' starting page</title>
     
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="js/ajaxfileupload.js"></script>
    <script type="text/javascript">
        function ajaxFileUpload()
        {
            var file = ['file1','file2'];  
              
            $.ajaxFileUpload
            (
                {
                    url:'upload_file_by_annotation!upload.action',//用于文件上传的服务器端请求地址
                    secureuri:false,//一般设置为false
                    fileElementId: file,// 文件id数组
                    dataType: 'JSON',//返回值类型 一般设置为json
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                       alert("success");
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert("fail");
                    }
                }
            );
              
            return false;
  
        }
 
    </script>
 
  </head>
   
  <body>
        <input type="file"  id="file1" name="file" />
        <input type="file"  id="file2" name="file" />
        <br />
        <input type="button" value="上传" onclick="return ajaxFileUpload();">
 
  </body>
</html>

【action代码】

注:其实这个说是annotation版本,但因为 没有特别要设置的,所以annotation也省了。

假如要跳转到其他页面,可自己加入annotation。简单annotaion使用例子可用参看上一篇文章:

《struts文件下载 annotation 注解版》http://www.cnblogs.com/xiaoMzjm/p/3879048.html

  1 package com.modelsystem.action;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.InputStream;
  8 import java.io.OutputStream;
  9 import java.util.List;
 10 
 11 import org.apache.struts2.ServletActionContext;
 12 
 13 /**
 14  * @描述 struts 多文件上传 annotation注解(零配置)+ ajaxfileupload + 异步 版本
 15  * @作者   小M
 16  * @博客 http://www.cnblogs.com/xiaoMzjm/
 17  * @时间 2014/07/30
 18  */
 19 public class UploadFileByAnnotationAction extends BaseAction {
 20     
 21     private static final long serialVersionUID = 1L;
 22     
 23     // 上传的文件,struts会自动帮我们填充至此,因为多文件,所以用List
 24     private List<File> file;
 25     
 26     // 上传的文件的文件名,因为多文件,所以用List
 27     private List<String> fileFileName;
 28     
 29     // 上传的文件的类型,因为多文件,所以用List
 30     private List<String> fileContentType;
 31      
 32     public List<File> getFile() {
 33         return file;
 34     }
 35  
 36     public void setFile(List<File> file) {
 37         this.file = file;
 38     }
 39  
 40     public List<String> getFileFileName() {
 41         return fileFileName;
 42     }
 43  
 44     public void setFileFileName(List<String> fileFileName) {
 45         this.fileFileName = fileFileName;
 46     }
 47  
 48     public List<String> getFileContentType() {
 49         return fileContentType;
 50     }
 51  
 52     public void setFileContentType(List<String> fileContentType) {
 53         this.fileContentType = fileContentType;
 54     }
 55  
 56     
 57     /**
 58      * 文件上传关键方法。
 59      */
 60     public String upload(){
 61         
 62         // 文件所放的文件夹。, 有关路径问题,请参考另一篇博文:http://www.cnblogs.com/xiaoMzjm/p/3878758.html
 63         String root = ServletActionContext.getServletContext().getRealPath("/")+"\upload\"; 
 64         
 65         //循环上传的文件
 66         for(int i = 0 ; i < file.size() ; i ++){
 67             
 68             InputStream is = null ;
 69             
 70             OutputStream os = null;
 71             try {
 72             // 获取当前遍历到的文件,new 一个文件输入流,连接到该文件。
 73             is = new FileInputStream(file.get(i));
 74              
 75             // new 一个文件,连接到要存储的文件夹处。
 76             File destFile = new File(root,this.getFileFileName().get(i));
 77              
 78             // new 一个输出流,连接到要存储的文件处。
 79             os = new FileOutputStream(destFile);
 80 
 81             // 字节流,规定可写入的字节数。
 82             byte[] buffer = new byte[is.available()];
 83             int length  = 0 ;
 84             
 85             // 开始写入文件
 86             while((length = is.read(buffer))>0){
 87                 os.write(buffer, 0, length);
 88             }
 89             
 90             } catch (Exception e) {
 91                 e.printStackTrace();
 92             } finally {
 93                 try {
 94                     is.close();
 95                 } catch (IOException e) {
 96                     e.printStackTrace();
 97                 }
 98                 try {
 99                     os.close();
100                 } catch (IOException e) {
101                     e.printStackTrace();
102                 }
103             }
104         }
105         return SUCCESS;
106     }
107 }
原文地址:https://www.cnblogs.com/xiaoMzjm/p/3879103.html