webwork/Struts 2 实现页面无刷新多文件上传

这个demo是用webwork实现的,原理上和用Struts 2完全一样。实现多文件上传和页面无刷新效果,用iframe技术实现了页面无刷新功能。上传成功后,后台向前台反馈上传成功的文件信息。

UploadAction.java 实现文件上传功能的action类。
package net.androidla.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionSupport;

public class UploadAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private File[] file;
	private String[] filename;
	private String name;
	private String msg;
	
	public String[] getFilename() {
		return filename;
	}

	public void setFilename(String[] filename) {
		this.filename = filename;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public File[] getFile() {
		return file;
	}

	public void setFile(File[] file) {
		this.file = file;
	}
	
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String upload() {
		StringBuilder str = new StringBuilder();
		List<String> filenamearr = new ArrayList<String>();
		for (int n = 0; n < filename.length; n ++) {
			if (!filename[n].equals("")) {
				filenamearr.add(filename[n]);
			}
		}
		
		File path = new File("C:/uploaddir");
		if (!path.exists()) {
			path.mkdirs();
		}
		FileOutputStream fos = null;
		FileInputStream fis = null;
		byte[] b = new byte[1024 * 10];
		int temp = 0;
		String name = null;
		String fname = null;
		int f = 0;
		for (int i = 0; i < file.length; i ++) {
			try {
				fname = filenamearr.get(i);
				f = fname.lastIndexOf("\\");
				name = f != -1 ? fname.substring(f + 1) : fname;
				fis = new FileInputStream(file[i]);
				fos = new FileOutputStream(path + File.separator + name);
				while ((temp = fis.read(b, 0, b.length)) != -1) {
					fos.write(b, 0, temp);
				}
				fos.flush();
				fos.close();
				fis.close();
				str.append(name + " 上传成功 ");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			HttpServletResponse res = ServletActionContext.getResponse();
			res.setCharacterEncoding("UTF-8");
			PrintWriter out = res.getWriter();
			out.println("<script type=\"text/javascript\">parent.callback('" + str.toString() + "')</script>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return NONE;
	}
}


webwork的配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xwork PUBLIC "-//OpenSymphony Group//XWork 1.1.1//EN" "http://www.opensymphony.com/xwork/xwork-1.1.1.dtd">
<xwork>
	<package name="upload" namespace="/upload" extends="webwork-default">
        <action name="upload" class="net.androidla.action.UploadAction" method="upload">
        	<!-- 
	        <interceptor-ref name="fileUploadStack"/>
	         -->
	        <interceptor-ref name="fileUpload" >
           		<param name="maximumSize">2048000</param> 
                <param name ="allowedTypes" > 
                    image/bmp,image/png,image/gif,image/jpeg,image/x-png,image/pjpeg,application/x-zip-compressed
                </param> 
            </interceptor-ref > 
            <interceptor-ref name="defaultStack" />
        </action>
    </package>
</xwork>



前台jsp文件:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/webwork" prefix="ww" %>
<%@ page import="com.opensymphony.xwork.ActionContext" %>
<%
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 'index.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">
	<script type="text/javascript">
		function getFileName(obj) {
			var file = document.getElementsByName("file");
			var filename = document.getElementsByName("filename");
			for (var i = 0; i < file.length; i ++) {
				if (obj == file[i]) {
					filename[i].value = file[i].value;
					break;
				}
			}
		}
		function callback(msg)
		{
		/*	document.getElementById("file").outerHTML = document.getElementById("file").outerHTML;*/
			document.getElementById("msg").innerHTML = "<font color=red>"+msg+"</font>";
		}
	</script>
  </head>
  
  <body>
	<form action="<%=path %>/upload/upload.action" id="form1" name="form1" encType="multipart/form-data" target="hidden_frame" method="post" >
	   	<input type="text" id="name" name="name" value="chen"><br>
		<input type="file" id="file1" name="file" style="width:450" onchange="getFileName(this);"><input type="hidden" id="filename1" name="filename"><br>
		<input type="file" id="file2" name="file" style="width:450" onchange="getFileName(this);"><input type="hidden" id="filename2" name="filename"><br>
		<input type="file" id="file3" name="file" style="width:450" onchange="getFileName(this);"><input type="hidden" id="filename3" name="filename"><br>
		<input type="file" id="file4" name="file" style="width:450" onchange="getFileName(this);"><input type="hidden" id="filename4" name="filename"><br>
		<input type="file" id="file5" name="file" style="width:450" onchange="getFileName(this);"><input type="hidden" id="filename5" name="filename"><br>
		<input type="file" id="file6" name="file" style="width:450" onchange="getFileName(this);"><input type="hidden" id="filename6" name="filename"><br>
		<INPUT type="submit" value="上传文件"><span id="msg"></span><br>
		<font color="red">支持"jpg", "jpeg", "gif", "zip"文件的上传</font>
		<iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>
	</form>
  </body>
</html>



猜你喜欢

转载自technique-digest.iteye.com/blog/1134583