Struts通过封装,可以非常简的实现文件上传,在页面上只需要提供一个<input type="file" name="属性名">元素,则Struts自动的将其提交的属性封装成一个org.apache.struts.upload.FormFile对象注入到对应ActionForm对象中,则在Action中直接可以通过ActionForm对象的FormFile属性来操作上传的文件流,从而实现上传功能,具体的示例如下:
首先,要先创建一个上传的页面视图文件index.jsp:
<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html:html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>文件上传</title>
</head>
<body>
<h2>文件上传示例</h2>
<html:form action="uploadAction" method="post" enctype="multipart/form-data">
<p>请选择您要上传的文件后提交:</p>
<html:file property="file" /><br /><br />
<html:submit>上传</html:submit>
</html:form>
<logic:notEmpty name="htmlFileForm" property="fname">
<p>刚上传的文件为:</p>
<ul>
<li>文件名:<bean:write name="htmlFileForm" property="fname" /></li>
<li>大小:<bean:write name="htmlFileForm" property="size" /></li>
</ul>
</logic:notEmpty>
</body>
</html:html>
注意这里使用的<html:form>标签的method属性,以及enctype属性的值。
其次创建一个封装该页面对应属性的ActionForm:
package test.upload.form;
import org.apache.struts.action.ActionForm;
import org.apache.struts.upload.FormFile;
public class FileForm extends ActionForm {
private static final long serialVersionUID = 1L;
/**
* The file that the user has uplaod.
*/
private FormFile file;
/**
* The name of the file - only for displaying results
*/
private String fname;
/**
* The size of the file - only for displaying results
*/
private String size;
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
}
注意这里ActionForm的属性名与index.jsp视图中的表单属性要相对应,可以看出这里的FormFile对象file,对应视图中的<html:file>标签的property属性。
接着创建处理表单上传的Action类:
package test.upload.action;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import test.upload.form.FileForm;
public class FileUploadAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String dir=servlet.getServletContext().getRealPath("/upload");
FileForm ff = (FileForm)form;
// org.apache.struts.upload.FormFile contains the uploaded file
FormFile file = ff.getFile();
// If no file was uploaded(e.g first form load), then display View
if(file == null) {
return mapping.findForward("success");
}
// Get the name and file Size
String fname = file.getFileName();
String size = Integer.toString(file.getFileSize()) + "bytes";
InputStream streamIn = file.getInputStream();
OutputStream streamOut = new FileOutputStream(dir+"/"+fname);
// Just output the real path of the uploaded file for test.
System.out.println("============"+dir+"/"+fname+"===========");
int bytesRead = 0;
byte[] buffer = new byte[8192];
while((bytesRead = streamIn.read(buffer, 0, 8192))!=-1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
ff.setFname(fname);
ff.setSize(size);
// Clean up our toys then done playing
file.destroy();
return mapping.findForward("success");
}
}
可以看出通过Struts的提供的FormFile对象就可以直接的操作上传的文件流,这样显得十分的方便。
注意:再运行本程序之前必须要保证WebContent目录下有一个upload目录。
最后配制相应的struts-config.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans> <form-bean name="htmlFileForm" type="test.upload.form.FileForm" /> </form-beans> <action-mappings> <action path="/uploadAction" name="htmlFileForm" type="test.upload.action.FileUploadAction"> <forward name="success" path="/index.jsp" /> </action> </action-mappings> </struts-config>最后运行截图:
选择文件后点击"上传":
程序的结构如下: