Struts2文件上传带进度条,虽然不是很完美

好久没有写东西,最近在做个项目,要用到文件h 传的,以前虽然也做上传,但是总觉得不好用 ,现在和队友合作做了一个带进度条的上传,觉得还行~~和大家分享一下。

首先说一下大概是这样实现的,在我们平时的上传表单里面,除了文件上传之外,也许还有其他的信息需要填写的,这样问题就来了:点击上传按钮之后,这个表单都封装并提交上去了,在上传完成后整个页面就跳转了。而且也不利于我们验证用户输入。很多人这样做的,把这2个操作分开,当然这样也行。。。

 我们这样做:一个普通页面(可以用于填写所有信息的),一个文件上传页面,一个上传成功页面(这个不怎么重要)

然后关键的就是:把文件上传的页面嵌入到普通页面里面去,相当于说文件上传实际是由上传页面独立完成,信息填写页面也独立成功信息填写,这里我们用iframe。

不多说,上代码:

 1、处理上传的Action

Java代码  收藏代码
  1. package org.yzsoft.upload.action;  
  2.   
  3. import java.io.*;    
  4. import org.apache.struts2.ServletActionContext;   
  5. import com.opensymphony.xwork2.ActionSupport;  
  6.    
  7. public class UploadAction extends ActionSupport {   
  8.     private static final int BUFFER_SIZE = 100;// 上传的字符流大小(单位:字节)  
  9.     // 用File来封装上传文件域对象  
  10.     private File file;  
  11.     // 保存文件的目录路径(通过自动注入)  
  12.     private static String ext; //文件后缀  
  13.     private static String fileFileName;  
  14.     private static float percent = 0;//百分比  
  15.        
  16.   
  17.     // 自己封装的一个把源文件对象复制成目标文件对象  
  18.   
  19.     private static void copy(File src, File dst) {   
  20.         InputStream in = null;  
  21.         OutputStream out = null;  
  22.         float completedSize = 0;//已经上传的大小  
  23.         float fileSize = 0;//文件总大小   
  24.         try {  
  25.             in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);  
  26.             out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);  
  27.             fileSize = in.available();  
  28.             byte[] buffer = new byte[BUFFER_SIZE];  
  29.             int len = 0;  
  30.             while ((len = in.read(buffer)) > 0) {  
  31.                 out.write(buffer, 0, len);  
  32.                 completedSize += (long) len;  
  33.                 percent = completedSize / fileSize * 100;//百分比计算  
  34.             }   
  35.         } catch (Exception e) {  
  36.             System.out.println(e);   
  37.         } finally {  
  38.             if (null != in) {  
  39.                 try {  
  40.                     in.close();  
  41.                 } catch (IOException e) {  
  42.                     System.out.println(e);  
  43.                 }  
  44.             }  
  45.             if (null != out) {  
  46.                 try {  
  47.                     out.close();  
  48.                 } catch (IOException e) {  
  49.                     System.out.println(e);  
  50.                 }  
  51.             }  
  52.         }   
  53.     }  
  54.   
  55.     public String sumPre() { //计算后百分比输回页面  
  56.         try {   
  57.             PrintWriter out = ServletActionContext.getResponse().getWriter();  
  58.             System.out.println(getFileFileName() + "                                             filename");   
  59.             out.print(percent);  
  60.         } catch (IOException e) {  
  61.             System.out.println("异常:" + e);  
  62.         }  
  63.         return null;  
  64.     }  
  65.     //上传的方法  
  66.     public String upload() {   
  67.         try {  
  68.             if (percent >= 99.9) {//这里保险起见我们设百分比》99.9就清0,避免进度条到了100%就停在那里不动的尴尬  
  69.                 percent = 0;  
  70.             }  
  71.             File srcfile = this.getFile();// 自动注入的方法取得文件域的对象  
  72.             // 根据服务器的文件保存地址和原文件名创建目录文件全路径  
  73.             String uploadPath = ServletActionContext.getServletContext().getRealPath("upload");// 上传路径   
  74.             ext = fileFileName.substring(fileFileName.lastIndexOf(".")).toLowerCase();// 取得后缀  
  75.             System.out.println("取得后缀        " + ext);   
  76.             File dstFile = new File(uploadPath, fileFileName);   
  77.             copy(srcfile, dstFile);  
  78.         } catch (Exception e) {  
  79.             System.out.println(e);  
  80.         }  
  81.         return "success";  
  82.   
  83.     }    
  84.     /**************/  
  85.     
  86.     public File getFile() {  
  87.         return file;  
  88.     }  
  89.   
  90.     public void setFile(File file) {  
  91.         this.file = file;  
  92.     }  
  93.    
  94.   
  95.     public String getFileFileName() {  
  96.         return fileFileName;  
  97.     }  
  98.   
  99.     public void setFileFileName(String fileFileName) {  
  100.         this.fileFileName = fileFileName;  
  101.     }   
  102. }  

 2、上传表单页面(就是我们平时普通的表单页面,样式有点乱。不理它了。嘻嘻~~~)

Java代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">   
  11.     <title>My JSP 'index.jsp' starting page</title>   
  12.   </head>   
  13.   <body>   
  14.       
  15. <form action="upload_doCreate.action"  method="post" name="form" >    
  16.     <table id="table2" width="99%" border="0" cellpadding="0" cellspacing="0">  
  17.       <tr>  
  18.         <th>文件上传</th>  
  19.       </tr>  
  20.       <tr>  
  21.         <td ><table border="0" cellpadding="0" cellspacing="0" style="100%">  
  22.             <tr>  
  23.               <td align="left">&nbsp;</td>  
  24.             </tr>  
  25.             <tr>  
  26.               <td width="100%">   
  27.               <table border="0" cellpadding="2" cellspacing="1" style="100%">   
  28.                   <tr>  
  29.                     <td align="right">文件名:</td>  
  30.                     <td><input type="text" id="filename" value=""/></td>  
  31.                   </tr>  
  32.                   <tr>  
  33.                     <td align="right">文件路径:</td>  
  34.                     <td><iframe style=" 400px;height: 25px" scrolling='no' frameborder='0' resizable='no' allowtransparency='true' cellspacing='0' border='0' src='fileupload.jsp' id='iframeupload'></iframe></td>  
  35.                   </tr>  
  36.                 </table>  
  37.                 <br />  
  38.                 </td>  
  39.             </tr>  
  40.           </table></td>  
  41.       </tr>  
  42.       <tr>  
  43.         <td colspan="2" align="center" height="50px">   
  44.           <input type="Submit" name="Submit" value="保存" class="button" />  
  45.           <input type="button" name="Submit2" value="返回" class="button" onclick="window.history.go(-1);"/></td>  
  46.       </tr>  
  47.     </table>   
  48. </form>  
  49.   </body>  
  50. </html>  

3、上传进度条页面(注意,这个是用一个iframe的源文件链接实现的)

Java代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()  
  6.             + path + "/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11.     <head>  
  12.         <base href="<%=basePath%>">   
  13.         <script type="text/javascript" src="jquery-1.6.2.min.js">  
  14. </script>  
  15.         <style type="text/css">  
  16. <!--  
  17. body {  
  18.     margin-left: 0px;  
  19.     margin-top: 0px;  
  20.     margin-right: 0px;  
  21.     margin-bottom: 0px;  
  22.     font-size: 14px;  
  23. }  
  24. -->  
  25. </style>  
  26.         <script type="text/javascript">  
  27. function aa() {   
  28.     $("#div1").hide();  
  29.     $("#div2").show();  
  30.     $.post("sumPre", {}, function(data) {//AJAX方式发送请求到Action的sumPre方法,计算后将百分比data返回来   
  31.         $("#img").attr("width", parseInt(data) * 1.5);//设置进度条长度,这里*1.5只是为了把进度条显示长一点,好看一点  
  32.             $("#p").html(parseInt(data) + "%");//进度百分比  
  33.         });  
  34.     window.setTimeout("aa()", 10);//定时执行  
  35. }  
  36. </script>  
  37.     </head>  
  38.   
  39.     <body>  
  40.         <div id="div1">  
  41.             <form name='aform1' method='post' action="fileUpload.action"  
  42.                 enctype="multipart/form-data">  
  43.                 <input name='file' type='file' />  
  44.                 <input type="submit" value="上传" onclick="return aa();" />  
  45.             </form>  
  46.         </div>  
  47.         <div id="div2" style=" 400px; display: none;">  
  48.             正在上传...  
  49.             <img alt="" src="13221820.gif" width="16" height="16">  
  50.             <img id="img" alt="" src="percent.jpg" width="1" height="5">  
  51.             <span id="p" style="position: absolute; right: 30%; top: 0px;"></span>  
  52.         </div>  
  53.     </body>  
  54. </html>  

4、上传成功后的页面(就是一个简单的页面)

Java代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.     <style type="text/css">  
  12.         <!--  
  13.         body {  
  14.             margin-left: 0px;  
  15.             margin-top: 5px;  
  16.             margin-right: 0px;  
  17.             margin-bottom: 0px;  
  18.             font-size: 14px;  
  19.         }  
  20.         -->  
  21.     </style>   
  22.   </head>   
  23.   <body>  
  24.     上传成功  
  25.   </body>  
  26. </html>  

5、Struts.xml 配置文件

Java代码  收藏代码
  1. <!DOCTYPE struts PUBLIC  
  2. "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  3. "http://struts.apache.org/dtds/struts-2.0.dtd">   
  4.     <!-- Author: yzx -->   
  5. <struts>   
  6.     <constant name="struts.multipart.maxSize" value="61440000000"></constant>  
  7.     <package name="fileUpload" namespace="/" extends="struts-default">  
  8.   
  9.         <action name="fileUpload" class="org.yzsoft.upload.action.UploadAction" method="upload">   
  10.             <result name="success">/filejd.jsp</result>  
  11.         </action>  
  12.         <action name="sumPre" class="org.yzsoft.upload.action.UploadAction" method="sumPre">  
  13.         </action>   
  14.     </package>   
  15. </struts>  
原文地址:https://www.cnblogs.com/564085446java/p/3836759.html