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

时间:2021-05-19 15:58:51

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

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

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

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

不多说,上代码:

1、处理上传的Action

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

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

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

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

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

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

  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. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  7. <html>
  8. <head>
  9. <base href="<%=basePath%>">
  10. <style type="text/css">
  11. <!--
  12. body {
  13. margin-left: 0px;
  14. margin-top: 5px;
  15. margin-right: 0px;
  16. margin-bottom: 0px;
  17. font-size: 14px;
  18. }
  19. -->
  20. </style>
  21. </head>
  22. <body>
  23. 上传成功
  24. </body>
  25. </html>

5、Struts.xml 配置文件

  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. <action name="fileUpload" class="org.yzsoft.upload.action.UploadAction" method="upload">
  9. <result name="success">/filejd.jsp</result>
  10. </action>
  11. <action name="sumPre" class="org.yzsoft.upload.action.UploadAction" method="sumPre">
  12. </action>
  13. </package>
  14. </struts>