在Struts2中实现文件上传非常的简单。利用Struts2所提供的组件可以很容易的完成。
在此我们通过一个简单的文件上传实例进行讲解。
首先在建立的Web Project工程中加入所需要的Struts2的.jar文件。在此特别需要以下两个类库文件,分别为:commons-io-1.1.jar和commons-fileupload-1.1.1.jar。因此在此项目中需要的Struts2的类库文件为如下所示:
下面开始实际的开发工作
因为采用了Struts2框架,所以需要像以前项目一样,在web.xml中加入struts2的配置,配置代码如下:
<?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>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts-cleanup</filter-name>
<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
</filter>
<filter-mapping>
<filter-name>struts-cleanup</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
首先建立上传文件的文件选择页面,此页面在此非常的简单,存在一个文件标题的描述输入框和文件选择组件
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%
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">
-->
</head>
<body>
<s:form action="fileUpLoad.action" method ="POST" enctype ="multipart/form-data">
<s:file name ="upFile" label ="FileName:" />
<s:textfield name ="title" label ="Title:" />
<s:submit align="left"/>
</s:form >
</body>
</html>
注意粗体部分,因为上传文件时,数据传输采用流的方式,所以需要设置enctype属性,设置为粗体的值。
窗体请求fileUpLoad控制器,下面当然是编写控制器了。注意在此文件选择组件的名称为upFile,此即为要上传得组件路经名称。在控制器中的很多地方要用到它
控制器代码如下:
package com.frank.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 org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UpLoadAction extends ActionSupport {
private static final int FILE_SIZE=16*1024;
private File upFile;
private String upFileContentType;
private String upFileFileName;
private String title;
public File getUpFile() {
return upFile;
}
public void setUpFile(File upFile) {
this.upFile = upFile;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public void setUpFileContentType(String upFileContentType) {
this.upFileContentType = upFileContentType;
}
public void setUpFileFileName(String upFileFileName) {
this.upFileFileName = upFileFileName;
}
public void upLoadFile(File source,File target){
InputStream in=null;
OutputStream out=null;
try{
in=new BufferedInputStream(new FileInputStream(source),FILE_SIZE);
out=new BufferedOutputStream(new FileOutputStream(target),FILE_SIZE);
byte[] image=new byte[FILE_SIZE];
while(in.read(image)>0){
out.write(image);
}
}catch(IOException ex){
ex.printStackTrace();
}finally{
try{
in.close();
out.close();
}catch(IOException ex){
}
}
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
System.out.println("hello");
String filePath=ServletActionContext.getServletContext().getRealPath("images")
+"/"+this.upFileFileName;
File targetFile=new File(filePath);
upLoadFile(upFile,targetFile);
return SUCCESS;
}
public String getUpFileFileName() {
return upFileFileName;
}
}
注意,针对于选择的上传文件,在控制器中存在三个set方法与此对应,分别为setUpFile、setUpFileContentType和setUpFileFileName,也就是说对于每个上传得文件,增加了ContentType和FileName的set和get方法。用来取得上传文件的文件类型名称和文件名称。而常规的UpFile的set和get方法获取和设置的是File类型。也就是要上传得文件。
在此增加了一个方法upLoad用来实现真正的文件上传操作。采用文件流的方式将上传得文件数据写入到目的地文件中。其实就是常规的文件流操作。
应该注意到,我们将文件上传到当前网站的images目录下,所以建立一个images目录即可。在编码中通过ServletActionContext.getServletContext().getRealPath("images")得到images的实际路经。
下面需要配置struts.xml了。当然需要在src下建立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="fileUpLoad" extends="struts-default">
<action name="fileUpLoad" class="com.frank.action.UpLoadAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/x-png
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
<result>success.jsp</result>
<result name="input">index.jsp</result>
</action>
</package>
</struts>
注意在控制器的配置中加入了两个拦截器。fileUpLoad拦截器负责拦截所选择的文件类型,通过参数allowedType来实现。在此我们能看明白,上传得文件类型必须为:image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/x-png 图片类型
同时需要加入defaultStack拦截器,这样在选择的文件违反条简单俄时候转发到input所指向的页面
当成功时,转发到success.jsp,此页面的职责是显示刚才上传得图片
代码非常的简单,使用<img>标记显示图片
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="/struts-tags" prefix="s" %>
<%
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 'success.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:property value="title"/>
<br>
<img src='images/<s:property value="upFileFileName"/>'>
</body>
</html>
现在可以开始测试了:
submit后,上传成功,显示图片
如果当时选择文件的时候,选择的类型违反了条件,不是图片,那么显示如下: