Struts2中的文件上传

struts2 文件上传

(1) 单文件上传

一.简介

Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form-data的请求,它需要调用其他请求解析器,将HTTP请求中的表单域解析出来。但Struts2在原有的上传解析器基础上做了进一步封装,更进一步简化了文件上传。
Struts2默认使用的是Jakarta的Common-FileUpload框架来上传文件,因此,要在web应用中增加两个Jar文件:commons-fileupload-1.2.jar和commons-io-1.3.1.jar。它在原上传框架上做了进一步封装,简化了文件上传的代码实现,取消了不同上传框架上的编程差异。
如果要改成其它的文件上传框架,可以修改struts.multipart.parser常量的值为cos/pell,默认值是jakata。并在classpath中增加相应上传组件的类库

例如配置成cos上传

struts.multipart.parser=cos

struts.multipart.maxSize=1024 指定文件的最大字结数

二.原理

不管用common-fileUPload框架,还是用cos,都是通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。

三.需要的jar包(默认使用commons-fileupload,如果使用cos,要将jar引进来)

commons-logging-1.1.jar
freemarker-2.3.8.jar
ognl-2.6.11.jar
struts2-core-2.0.6.jar
xwork-2.0.1.jar
commons-io-1.3.1.jar
commons-fileupload-1.2.jar

四.实例

1.首先,创建上传页面

Html代码
<%@page language="java" contentType = "text/html; charset=utf-8" pageEncoding = "utf-8"%>    
<%@taglib prefix="s" uri ="/struts-tags"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP 'FileUpload.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">
-->

</head>

<body>
<s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data">
<s:fielderror />
<s:file name ="upload"/>
<s:submit />
</s:form >

</body>
</html>


<%@page language="java" contentType = "text/html; charset=utf-8" pageEncoding = "utf-8"%> 
<%@taglib prefix="s" uri ="/struts-tags"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP 'FileUpload.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">
-->

</head>

<body>
<s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data">
<s:fielderror />
<s:file name ="upload"/>
<s:submit />
</s:form >

</body>
</html>


2.action

Java代码
package com;   

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 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 File upload;

private String uploadContentType;

private String uploadFileName;

private String imageFileName;

public String getUploadContentType() {
return uploadContentType;
}

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

public File getUpload() {
return upload;
}

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

public String getUploadFileName() {
return uploadFileName;
}

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

public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}

public String getImageFileName() {
return imageFileName;
}

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

@Override
public String execute() {
System.out.println(uploadFileName);

imageFileName = System.currentTimeMillis() + uploadFileName.substring(uploadFileName.lastIndexOf("."));
File imageFile = new File(ServletActionContext.getServletContext()
.getRealPath("/uploadImages")
+ "/" + imageFileName);
copy(upload, imageFile);
return SUCCESS;
}

}

package com;

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 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 File upload;

private String uploadContentType;

private String uploadFileName;

private String imageFileName;

public String getUploadContentType() {
return uploadContentType;
}

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

public File getUpload() {
return upload;
}

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

public String getUploadFileName() {
return uploadFileName;
}

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

public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}

public String getImageFileName() {
return imageFileName;
}

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

@Override
public String execute() {
System.out.println(uploadFileName);

imageFileName = System.currentTimeMillis() + uploadFileName.substring(uploadFileName.lastIndexOf("."));
File imageFile = new File(ServletActionContext.getServletContext()
.getRealPath("/uploadImages")
+ "/" + imageFileName);
copy(upload, imageFile);
return SUCCESS;
}

}


表单的enctype ="multipart/form-data,与一般的上传一样.

<s:file name="upload">会将upload绑定到action的upload,其次他还会将上传记文件的MIME类型绑定到uploadContentType,文件名绑定到uploadFileName中,他们是通过

setUploadContentType和setUploadFileName进行绑定的,下面进行的多文件上传也是同个道理,不过要用数组或者是list来进行绑定,然后多个文件的MIME类型也会绑定到以数组

名字加ContentType和FileName的字符串数组中。 比如说上传的文件的数组名为:File[] uploads,则它们的MIME类型绑定的对应的数组是uploadsFileName和uploadsContentType.

3.struts.xml的配置

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>
<constant name="struts.multipart.saveDir" value="/tmp" />
<package name="fileUploadDemo" extends="struts-default">
<action name ="fileUpload" class ="com.FileUploadAction">
<!-- 验证上传文件的类型 -->
<interceptor-ref name ="fileUpload">
<param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param>
</interceptor-ref>
<interceptor-ref name ="defaultStack"/>
<!-- 如果加入了验证上传文件的类型,必须要加input -->
<result name ="input" >/fileUpload.jsp</result>
<result name ="success">/showUpload.jsp </result>
</action>
</package>
</struts>

<?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>
<constant name="struts.multipart.saveDir" value="/tmp" />
<package name="fileUploadDemo" extends="struts-default">
<action name ="fileUpload" class ="com.FileUploadAction">
<!-- 验证上传文件的类型 -->
<interceptor-ref name ="fileUpload">
<param name ="allowedTypes">image/bmp,image/png,image/gif,image/jpeg,image/jpg</param>
</interceptor-ref>
<interceptor-ref name ="defaultStack"/>
<!-- 如果加入了验证上传文件的类型,必须要加input -->
<result name ="input" >/fileUpload.jsp</result>
<result name ="success">/showUpload.jsp </result>
</action>
</package>
</struts>


4.最后是web.xml的配置

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

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>



(2) 多文件上传

多文件上传
与单文件上传相似,Struts 2实现多文件上传也很简单。你可以将多个<s:file />绑定Action的数组或列表。如下例所示。

< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >
< s:file label ="File (1)" name ="upload" />
< s:file label ="File (2)" name ="upload" />
< s:file label ="FIle (3)" name ="upload" />
< s:submit />
</ s:form > 清单14 多文件上传JSP代码片段
如果你希望绑定到数组,Action的代码应类似:

private File[] uploads;
private String[] uploadSFileName;
private String[] uploadSContentType;

多文件上传数组绑定Action代码片段
如果你想绑定到列表,则应类似:

private List < File > uploads = new ArrayList < File > ();
private List < String > uploadSFileName = new ArrayList < String > ();
private List < String > uploadSContentType = new ArrayList < String > ();
多文件上传列表绑定Action代码片段
总结
在Struts 2中实现文件上传的确是轻而易举,您要做的只是使用<s:file />与Action的属性绑定。这又一次有力地证明了Struts 2的简单易用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值