`
hdxiong
  • 浏览: 371136 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Struts2实现的多文件上传例子

    博客分类:
  • SSH
阅读更多
文件上传的原理:
表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:
      1)application/x-www-form-urlencoded:这是默认编码方式,它只处理表单域里的value属性值,采用这种编码方式的表单会将表单域的值处理成URL编码方式。
      2)multipart/form-data:这种编码方式的表单会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数里。
      3)text/plain:这种方式主要适用于直接通过表单发送邮件的方式。
文件上传是web应用经常用到的一个知识。原理是,通过为表单元素设置enctype=”multipart/form-data”属性,让表单提交的数据以二进制编码的方式提交,在接收此请求的Servlet中用二进制流来获取内容,就可以取得上传文件的内容,从而实现文件的上传。
在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件(http://commons.apache.org/fileupload/),另一个是Oreilly组织的COS框架(http://www.servlets.com/cos/)。利用这两个框架都能很方便的实现文件的上传。

以下是实现的全部代码,仅供参考:

    JAR需求:除了Struts2的基本jar必须之外加入commons-fileupload.jar和commons-io.jar即可!

一、upload.jsp:
<%@ page language="java" contentType="text/html; charset=GB2312"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<html>
	<head>
		<title>多文件上传</title>
	</head>
	<body>
		<font color="red"><s:fielderror /> </font>
		<form action="upload.action" method="POST"
			enctype="multipart/form-data">
			<!-- 设置二个文件域,名字相同 -->
			选择第一个文件:
			<input type="file" name="upload" size="50" />
			<br />
			选择第二个文件:
			<input type="file" name="upload" size="50" />
			<input type="submit" value=" 上传 " />
		</form>
	</body>
</html>

二、struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
	<include file="struts-default.xml" />
	<package name="struts-upload" extends="struts-default">
		<action name="upload" class="uploadAction">
			<interceptor-ref name="fileUpload">
				<param name="allowedTypes">
			image/bmp,image/png,image/gif,image/jpeg
				</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack" ></interceptor-ref>
			<result name="success">/manage/success.jsp</result>
			<result name="input">upload.jsp</result>
		</action>
	</package>
</struts>

三、UploadAction.java:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

/**
 * 处理多文件上传的Action类
 * 
 * @authorqiujy
 * @version1.0
 */
public class UploadAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final int BUFFER_SIZE = 16 * 10240;

	private String dstPath = null;
	private InputStream in = null;
	private OutputStream out = null;

	/**
	 * 用File数组来封装多个上传文件域对象
	 */
	private File[] upload;
	/**
	 * 用String数组来封装多个上传文件名
	 */
	private String[] uploadFileName;
	/**
	 * 用String数组来封装多个上传文件类型
	 */
	private String[] uploadContentType;
	/**
	 * 保存上传的文件(spring注入)
	 */
	private String saveFilesDir;
	/**
	 * 保存上传的图片(srping注入)
	 */
	private String saveImageDir;

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public void setSaveFilesDir(String saveFilesDir) {
		this.saveFilesDir = saveFilesDir;
	}

	public void setSaveImageDir(String saveImageDir) {
		this.saveImageDir = saveImageDir;
	}

	// 自己封装的一个把源文件对象复制成目标文件对象
	private void copy(File src, File dst) throws Exception {
		try {
			in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
			out = new BufferedOutputStream(new FileOutputStream(dst),
					BUFFER_SIZE);
			byte[] buffer = new byte[BUFFER_SIZE];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				in.close();
			}
			if (null != out) {
				out.close();
			}
		}
	}

	public String execute() throws Exception {
		// 处理每个要上传的文件
		for (int i = 0; i < upload.length; i++) {
			if (uploadFileName[i].length() != 0) {
				// 根据服务器的文件保存地址和原文件名创建目录文件全路径
				if (uploadContentType[i].startsWith("image")) {
					dstPath = ServletActionContext.getServletContext()
							.getRealPath(saveImageDir + uploadFileName[i]);
				} else {
					dstPath = ServletActionContext.getServletContext()
							.getRealPath(saveFilesDir + uploadFileName[i]);
				}
				if (upload[i] != null)
					copy(upload[i], new File(dstPath));
			}
		}
		return SUCCESS;
	}
}


注意:页面中上传标签<s:file name="xxx" />对应Action类里面的xxx、xxxContentType和xxxFileName三个属性。

四、web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	<!-- 配置struts2 -->
	<filter>
		<filter-name>struts-cleanup</filter-name>
		<filter-class>
		org.apache.struts2.dispatcher.ActionContextCleanUp
		</filter-class>
	</filter>
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>
		org.apache.struts2.dispatcher.FilterDispatcher
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts-cleanup</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 加载spring配置文件 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/spring-configs/config-*.xml</param-value>
	</context-param>
	<!-- 配置spring监听器 -->
	<listener>
		<listener-class>
	org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

注意:两个filter-mapping的顺序不要颠倒了!

五、在struts.properties中设置上传参数:
##### temporary directory #####
struts.multipart.saveDir=C\:/temp
##### default(CommonsFileUpload) #####
#struts.multipart.parser=
##### default(2M) #####
struts.multipart.maxSize= 10485760

六、在message_zh_CN.properties中设置错误消息:
struts.messages.error.uploading=上传文件失败!
struts.messages.error.file.too.large=上传文件太大!
struts.messages.error.content.type.not.allowed=赞不支持该格式上传!

注意:该错误消息必须写在国际化中才有效!
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics