JQuery和Struts实现Ajax文件上传

来源:互联网 发布:ubuntu root 没有声音 编辑:程序博客网 时间:2024/05/25 08:13

使用的框架分别是是struts1.3 jQuery1.3 ajaxupload.3.2.js(一个JQuery的插件,实现Ajax上传的效果)。


首先说下使用的框架和插件:

Struts1.3   jQuery1.3   ajaxupload.3.2.js(一个JQuery的插件,实现Ajax上传的效果)

COS(O’relly的一个性能很棒的上传组件)

JSP页面:

  1. <%@ page language="java"  pageEncoding="UTF-8"%> 
  2. <%@ include file="../../common/taglibs.jsp" %> 
  3. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
  4. <html> 
  5.   <head> 
  6.    <script type="text/javascript" src="${basePath }/script/jquery.js"></script> 
  7.    <script type="text/javascript" src="${basePath }/script/ajaxupload.3.2.js"></script> 
  8.     <title>Ajax文件上传示例</title> 
  9.     <style type="text/css"> 
  10.      #loading,ol{  
  11.       font-size:14px;  
  12.       display:none;  
  13.       color:orange;  
  14.       display:none;  
  15.      }  
  16.      ol{  
  17.       display:block;  
  18.      }  
  19.     </style> 
  20.  <script type="text/javascript"> 
  21.   $(function(){  
  22.      
  23.    new AjaxUpload("#fileButton",{  
  24.     action:"${basePath}/file.do?method=upload",  
  25.     autoSubmit:true,  
  26.     name:"myfile",  
  27.     onSubmit:function(file, extension){  
  28.      if (extension && /^(pdf|jpg|png|jpeg|gif)$/.test(extension))  
  29.      {  
  30.       $("#loading").html('<img src="${basePath}/images/loading.gif">');  
  31.       $("#loading").show();  
  32.       $("#fileButton").attr("disabled","disabled");  
  33.      }  
  34.      else  
  35.      {  
  36.       $("#loading").html("你所选择的文件不受系统支持");  
  37.       $("#loading").show();  
  38.       return false;  
  39.      }  
  40.     },  
  41.     onComplete:function(file, extension){  
  42.      $("#loading").html("文件上传成功");  
  43.      $("#loading").show();  
  44.      $("#fileButton").removeAttr("disabled");  
  45.     }  
  46.    });  
  47.      
  48.      
  49.    new Ajax_upload('#button3', {  
  50.     action: '${basePath}/file.do?method=upload',  
  51.     name: 'myfile',  
  52.     autoSubmit:true,  
  53.     onComplete : function(file, extension){  
  54.      $('<li></li>').appendTo($('.files')).text(file);  
  55.     }   
  56.    });  
  57.   });  
  58.  </script> 
  59.   </head> 
  60.     
  61.   <body>   
  62.     <input type="button" value="请选择您的照片" id="fileButton"/> 
  63.     <div id="loading"><img src="${basePath}/images/loading.gif"></div> 
  64.     <hr/> 
  65.      
  66.     <form action="#" method="post"> 
  67.  
  68.   <input id="button3" type="file" /> 
  69.   <p>上传成功的文件有:</p> 
  70.   <ol class="files"></ol> 
  71.   <p> 
  72.    <input class="submit" type="submit" value="表单提交"/>   
  73.   </p> 
  74.  
  75.  </form> 
  76.  
  77.   </body> 
  78. </html> 
  79. StrutsAction代码:package com.kay.crm.web;  
  80.  
  81. import javax.servlet.http.HttpServletRequest;  
  82. import javax.servlet.http.HttpServletResponse;  
  83.  
  84. import org.apache.struts.action.ActionForm;  
  85. import org.apache.struts.action.ActionForward;  
  86. import org.apache.struts.action.ActionMapping;  
  87. import org.apache.struts.actions.DispatchAction;  
  88. import org.springframework.stereotype.Controller;  
  89.  
  90. import com.kay.common.util.CosUtil;  
  91.  
  92. @Controller("/file")  
  93. public class FileUploadAction extends DispatchAction {  
  94.  
  95.  public ActionForward upload(ActionMapping mapping, ActionForm form,  
  96.    HttpServletRequest request, HttpServletResponse response) throws Exception {  
  97.     
  98.  
  99.   String fileName = CosUtil.upload(request);  
  100.   System.out.println(fileName);  
  101.     
  102.   return null;  
  103.  }  
  104. }Cos的工具类:package com.kay.common.util;  
  105.  
  106. import java.io.File;  
  107. import java.io.IOException;  
  108. import java.util.Enumeration;  
  109.  
  110. import javax.servlet.http.HttpServletRequest;  
  111.  
  112. import com.oreilly.servlet.MultipartRequest;  
  113.  
  114. public class CosUtil {  
  115.  
  116.  @SuppressWarnings({ "deprecation", "unchecked" })  
  117.  public static String upload(HttpServletRequest request) throws IOException  
  118.  {  
  119.   //存绝对路径  
  120.   //String filePath = "C://upload";  
  121.   //存相对路径  
  122.   String filePath = request.getRealPath("/")+"upload";  
  123.   File uploadPath = new File(filePath);  
  124.   //检查文件夹是否存在 不存在 创建一个  
  125.   if(!uploadPath.exists())  
  126.   {  
  127.    uploadPath.mkdir();  
  128.   }  
  129.   //文件最大容量 5M  
  130.   int fileMaxSize = 5*1024*1024;  
  131.    
  132.   //文件名  
  133.   String fileName = null;  
  134.   //上传文件数  
  135.   int fileCount = 0;  
  136.   //重命名策略  
  137.   RandomFileRenamePolicy rfrp=new RandomFileRenamePolicy();  
  138.   //上传文件  
  139.   MultipartRequest mulit = new MultipartRequest(request,filePath,fileMaxSize,"UTF-8",rfrp);  
  140.     
  141.   String userName = mulit.getParameter("userName");  
  142.   System.out.println(userName);  
  143.     
  144.   Enumeration filesname = mulit.getFileNames();  
  145.        while(filesname.hasMoreElements()){  
  146.             String name = (String)filesname.nextElement();  
  147.             fileName = mulit.getFilesystemName(name);  
  148.             String contentType = mulit.getContentType(name);  
  149.               
  150.             if(fileName!=null){  
  151.              fileCount++;  
  152.             }  
  153.             System.out.println("文件名:" + fileName);  
  154.             System.out.println("文件类型: " + contentType);  
  155.               
  156.        }  
  157.        System.out.println("共上传" + fileCount + "个文件!");  
  158.          
  159.        return fileName;  
  160.  }  
  161. }Cos上传组件用到的重命名策略类:package com.kay.common.util;  
  162.  
  163. import java.io.File;  
  164. import java.util.Date;  
  165.  
  166. import com.oreilly.servlet.multipart.FileRenamePolicy;  
  167.  
  168. public class RandomFileRenamePolicy implements FileRenamePolicy {  
  169.  
  170.  public File rename(File file) {  
  171.    String body="";  
  172.       String ext="";  
  173.       Date date = new Date();  
  174.       int pot=file.getName().lastIndexOf(".");  
  175.       if(pot!=-1){  
  176.           bodydate.getTime() +"";  
  177.           ext=file.getName().substring(pot);  
  178.       }else{  
  179.           body=(new Date()).getTime()+"";  
  180.           ext="";  
  181.       }  
  182.       String newName=body+ext;  
  183.       file=new File(file.getParent(),newName);  
  184.       return file;  
  185.  
  186.  }