当前位置: 代码迷 >> Web前端 >> struts2 实现文件的下传
  详细解决方案

struts2 实现文件的下传

热度:119   发布时间:2012-10-08 19:54:56.0
struts2 实现文件的上传
首先将struts2的两个jar包添加到工程目录中:
commons-fileupload-1.2.1.jar
commons-io-1.3.2.jar
除了这两个jar包外,还需要添加struts2所需要的jar包;
上传的界面index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%
	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">
		<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	<%=request.getAttribute("name")%>
	<s:property value="tuser.name"/>
	-->
	</head>
	<body>
		<s:form action="fileUpload.action" method="POST"
			enctype="multipart/form-data"> 
                                                     你好${name},欢迎!当前浏览器的版本为${header["User-Agent"]}<br />
                     Struts2文件上传: <input type="file" name='myFile' />
                      <s:textfield name ="caption" label ="Caption" />      
                     <s:submit value="上传"></s:submit>
		</s:form>
	</body>
</html>



web.xml文件的配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<filter>
		<filter-name>struts</filter-name>
		<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
	</filter>
	
	<filter-mapping>
	<filter-name>struts</filter-name>
	<url-pattern>*.action</url-pattern>
	</filter-mapping>
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


strust2.xml文件的配置:
<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<package name = "struts2 " namespace="/s" extends="struts-default">
		<action name = "FirstAction_*" class="Struts2.Action.FirstAction" method="{1}">
			<result name="positive">/yes.jsp</result>
			<result name="negative">/no.jsp</result>
		</action>
	</package>
	 <package name ="fileUploadDemo" extends ="struts-default"> 
        <action name ="fileUpload" class ="Struts2.Action.FileUploadAction"> 
            <interceptor-ref name ="fileUploadStack"/> 
            <result name ="success">/yesFile.jsp </result> 
        </action > 
    </package > 
</struts>

在FileUpload.jsp中,先将表单的提交方式设为POST,然后将enctype设为multipart/form-data,这并没有什么特别之处。接下来,<s:file/>标志将文件上传控件绑定到Action的myFile属性。


上传文件的action:
package Struts2.Action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class FileUploadAction extends ActionSupport {
	private static final long serialVersionUID = 572146812454l;
	private static final int BUFFER_SIZE = 1024 * 1024;

	private File myFile;
	private String contentType;
	private String fileName;
	private String imageFileName;
	private String caption;

	public void setMyFileContentType(String contentType) {
		this.contentType = contentType;
	}

	public void setMyFileFileName(String fileName) {
		this.fileName = fileName;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public String getCaption() {
		return caption;
	}

	public void setCaption(String caption) {
		this.caption = caption;
	}

	private static void copy(File src, File dst) {
		try {
			InputStream in = null;
			OutputStream out = null;
			try {
				in = new BufferedInputStream(new FileInputStream(src),
						BUFFER_SIZE);
				out = new BufferedOutputStream(new FileOutputStream(dst),
						BUFFER_SIZE);
				byte[] buffer = new byte[BUFFER_SIZE];
				while (in.read(buffer) > 0) {
					out.write(buffer);
				}
			} finally {
				if (null != in) {
					in.close();
				}
				if (null != out) {
					out.close();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String getExtention(String fileName) {
		int pos = fileName.lastIndexOf(".");
		System.out.println("pos::::::" + pos + "====filename.subString():"
				+ fileName.substring(pos));
		return fileName.substring(pos);
	}

	@Override
	public String execute(){
		try {
			imageFileName = new Date().getTime() + getExtention(fileName);
			File imageFile = new File(ServletActionContext.getServletContext()
					.getRealPath("/UploadImages")
					+ "/" + imageFileName);
			if (!imageFile.exists()) { // 若不存在目标文件,则创建
				imageFile.getParentFile().mkdirs();
				imageFile.createNewFile();
			} else { // 若存在,则删除后重新创建
				imageFile.delete();
				imageFile.createNewFile();
			}
			copy(myFile, imageFile);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SUCCESS;
	}

}

在FileUploadAction中我分别写了setMyFileContentType、setMyFileFileName、setMyFile和setCaption四个Setter方法,后两者很容易明白,分别对应FileUpload.jsp中的<s:file/>和<s:textfield/>标志。但是前两者并没有显式地与任何的页面标志绑定,那么它们的值又是从何而来的呢?其实,<s:file/>标志不仅仅是绑定到myFile,还有myFileContentType(上传文件的MIME类型)和myFileFileName(上传文件的文件名,该文件名不包括文件的路径)。因此,<s:file name="xxx" />对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。

FileUploadAction作用是将浏览器上传的文件拷贝到WEB应用程序的UploadImages文件夹下,新文件的名称是由系统时间与上传文件的后缀组成,该名称将被赋给imageFileName属性,以便上传成功的跳转页面使用。






上传成功后显示出来的jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<title>Struts 2 File Upload</title>
	</head>
	<body>
		<div style="padding: 3px; border: solid 1px #cccccc; text-align: center">
			<img src='UploadImages/<s:property value="imageFileName"/>'/>
			<br />上传成功:
			<s:property value="caption" />
		</div>
	</body>
</html>
  相关解决方案