Struts2实现的多文件上传例子

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

[B]以下是实现的全部代码,仅供参考:[/B]
[list]
JAR需求:[B]除了Struts2的基本jar必须之外加入commons-fileupload.jar和commons-io.jar即可![/B]
[/list]
一、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;
}
}


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

四、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>

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

五、在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=赞不支持该格式上传!

[b]注意:该错误消息必须写在国际化中才有效![/b]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值