实现原理
Struts 2是通过Commons FileUpload文件上传。Commons FileUpload通过将HTTP的数据保存到临时文件夹,然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。
具体实现
前段时间Apache发布了Struts 2.0.6 GA,所以本文的实现是以该版本的Struts作为框架的。以下是例子所依赖类包的列表:
目录结构:
创建文件上传页面FileUpload.jsp
<%
...
@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"
%>

<%
...
@ taglib prefix="s" uri="/struts-tags"
%>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
Struts 2 File Upload
</
title
>
</
head
>
<
body
>
<
s:fielderror
/>
<
div
>
<
p
><
b
>
Single file upload
</
b
></
p
>
<
s:form
action
="fileUpload"
method
="POST"
enctype
="multipart/form-data"
>
<
s:file
name
="myFile"
label
="Image File"
/>
<
s:textfield
name
="caption"
label
="Caption"
/>
<
s:submit
/>
</
s:form
>
</
div
>
<
div
>
<
p
><
b
>
Multiple files upload
</
b
></
p
>
<
s:form
action
="multiplefileUpload"
method
="POST"
enctype
="multipart/form-data"
>
<
s:file
label
="File(1)"
name
="uploads"
/>
<
s:file
label
="File(2)"
name
="uploads"
/>
<
s:file
label
="FIle(3)"
name
="uploads"
/>
<
s:file
label
="FIle(4)"
name
="uploads"
/>
<
s:textfield
name
="caption"
label
="Caption"
/>
<
s:submit
/>
</
s:form
>
</
div
>
</
body
>
</
html
>
创建FileUploadAction.java
package
fileupload;
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.ArrayList;
import
java.util.Date;
import
java.util.List;
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 = 64 * 1024;
private File myFile;
private String contentType;
private String fileName;
private String imageFileName;
private String caption;
private File[] uploads;
private String[] uploadFileNames;
private String[] uploadContentTypes;
private List imageFileNames = new ArrayList() ;

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

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

public void setMyFile(File myFile) ...{
System.out.println("this is setMyFile[]");
this.myFile = myFile;
}

public String getImageFileName() ...{
return imageFileName;
}

public String getCaption() ...{
return caption;
}

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

public File[] getUploads() ...{
return this.uploads;
}

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

public String[] getUploadsFileName() ...{
return this.uploadFileNames;
}

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

public String[] getUploadsContentType() ...{
return this.uploadContentTypes;
}

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

public List getImageFileNames() ...{
return imageFileNames;
}

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(".");
return fileName.substring(pos);
}

public String execute() ...{
if (this.fileName != null) ...{
imageFileName = new Date().getTime() + getExtention(fileName);
File imageFile = new File(ServletActionContext.getServletContext()
.getRealPath("/upload/UploadImages")
+ "/" + imageFileName);
copy(myFile, imageFile);
return SUCCESS;
} else ...{

for (int i = 0; i < this.uploads.length; i++) ...{
System.out.println(this.uploadFileNames[i]);
imageFileName = new Date().getTime() + i + getExtention(this.uploadFileNames[i]);
imageFileNames.add(imageFileName);
File imageFile = new File(ServletActionContext.getServletContext().getRealPath("/upload/UploadImages")+ "/" + imageFileName);
copy(this.uploads[i], imageFile);
}
return SUCCESS;
}
}
}
上传成功的页面:
ShowUpload.jsp
<%
...
@ page language="java" contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"
%>

<%
...
@ taglib prefix="s" uri="/struts-tags"
%>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
Struts 2 File Upload
</
title
>
</
head
>
<
body
>
<
div
style
="padding:3px;width=100px"
>
<
fieldset
>
<
legend
>
UploadImage:
<
b
>
<
s:property
value
="caption"
/></
b
></
legend
>
<
img
src
='UploadImages/<s:property
value
="imageFileName"
/>
'/>
</
fieldset
>
</
div
>
</
body
>
</
html
>
ShowMultipleUpload.jsp
<%
...
@ page language="java" contentType="text/html;charset=UTF-8"
pageEncoding="UTF-8"
%>

<%
...
@ taglib prefix="s" uri="/struts-tags"
%>
<!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<
html
xmlns
="http://www.w3.org/1999/xhtml"
>
<
head
>
<
title
>
Struts 2 File Upload
</
title
>
</
head
>
<
body
>
<
div
style
="padding:3px;width=100px"
>
<
fieldset
>
<
legend
>
UploadImage:
<
b
>
<
s:property
value
="caption"
/></
b
></
legend
>
<
s:iterator
value
="imageFileNames"
>
<
img
src
='UploadImages/<s:property
/>
'/>
</
s:iterator
>
</
fieldset
>
</
div
>
</
body
>
</
html
>
Action的配置文件:
<
package
name
="fileUploadDemo"
extends
="struts-default"
namespace
="/upload"
>
<
action
name
="fileUpload"
class
="fileupload.FileUploadAction"
>
<
interceptor-ref
name
="fileUpload"
>
<
param
name
="allowedTypes"
>
image/bmp,image/png,image/gif,image/jpeg
</
param
>
</
interceptor-ref
>
<
interceptor-ref
name
="fileUploadStack"
/>
<
result
name
="input"
>
FileUpload.jsp
</
result
>
<
result
name
="success"
>
ShowUpload.jsp
</
result
>
</
action
>
<
action
name
="multiplefileUpload"
class
="fileupload.FileUploadAction"
>
<
result
name
="input"
>
FileUpload.jsp
</
result
>
<
result
name
="success"
>
ShowMultipleUpload.jsp
</
result
>
</
action
>
</
package
>
web.xml配置文件:
<?
xml version="1.0" encoding="UTF-8"
?>
<
web-app
id
="WebApp_9"
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"
>

<
display-name
>
Struts 2 Fileupload
</
display-name
>

<
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.html
</
welcome-file
>
</
welcome-file-list
>

</
web-app
>
运行结果:
地址:http://localhost:8080/s2/upload/FileUpload.jsp
Single file upload Result
本文介绍如何使用Struts2框架实现单文件和多文件上传的功能。通过详细步骤及代码示例展示了文件上传的实现过程,包括配置文件、Action处理及上传页面的设计。

745





