struts上传文件
1:Html代码
<%@ page contentType="text/html;charset=GBK" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>一个上传文件的例子</title>
</head>
<BODY>
<h1>一个上传文件的例子</h1>
<html:errors/><br>
<html:form action="uploadfile.do" enctype="multipart/form-data">
<html:file property="file" /><br><br>
<html:submit></html:submit>
</html:form>
</BODY></html>
这里必须注意:<html:form>标签元素中必须加上 enctype="multipart/form-data"这个属性,否则会报出参数不匹配的错误。即使将这个struts标签换成HTML的<form />标签,也还是要加上这个属性。同时,method属性值必须为post,否则也会报错。
2:sucess.jsp代码
Html代码
<%@ page contentType="text/html;charset=GBK" language="java" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<h1>上传成功...</h1><html:link forward="index">返回</html:link>
</html>
3:ActionForm类代码:UploadFileForm.java
Java代码
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.0/xslt/JavaClass.xsl
package testfile.forms;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionError;
import org.apache.struts.upload.FormFile;
import org.apache.struts.upload.MultipartRequestHandler;
/**
* MyEclipse Struts
* Creation date: 11-14-2005
*
* XDoclet definition:
* @struts.form name="uploadForm"
*/
public class UploadFileForm extends ActionForm {
private FormFile file=null;}
//private String fname;
//private String size;
//private String url;
public FormFile getFile(){
return file;
}
public void setFile(FormFile file){
this.file=file;
}
//**************验证文件如果为空则返回*****************
public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {
ActionErrors errors=new ActionErrors();
if(file==null || file.getFileSize()<5 || file.getFileName()==null){
errors.add("file",new ActionError("error.file.null"));
}
return errors;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
4:Action类中的代码:UploadFileAction.java
Java代码
//Created by MyEclipse Struts
// XSL source (default): platform:/plugin/com.genuitec.eclipse.cross.easystruts.eclipse_4.0.0/xslt/JavaClass.xsl
package testfile.actions;
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 org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.upload.*;
import testfile.forms.*;
import java.io.*;
/**
* MyEclipse Struts
* Creation date: 11-14-2005
*
* XDoclet definition:
* @struts.action validate="true"
*/
public class UploadFileAction extends Action{
public ActionForward execute (
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
ActionErrors errors=new ActionErrors();
UploadFileForm hff=(UploadFileForm)form;
FormFile file=hff.getFile();
//*************如果ActionForm中没验证则加上这段*****************
//if(file==null || file.getFileSize()<10 || file.getFileName()==null){
// errors.add("file",new ActionError("error.file.null"));
// saveErrors(request,errors);
// return (new ActionForward(mapping.getInput()));
//}
//*************取得上传文件的信息****************
String dir=servlet.getServletContext().getRealPath("/upload");
String fname=file.getFileName();
String size=Integer.toString(file.getFileSize())+"bytes";
String url=dir+"\\"+fname;
//*************限制非图片文件的上传*******************
String fileType=(fname.substring(fname.lastIndexOf('.')+1)).toLowerCase();
if((!fileType.equals("jpg")) && (!fileType.equals("bmp")) && (!fileType.equals("gif")) && (!fileType.equals("jpeg"))){
errors.add("filetype",new ActionError("error.file.type"));
saveErrors(request,errors);
return (new ActionForward(mapping.getInput()));
}
//*************限制文件不能超过2M******************
if(file.getFileSize()>2097152){
errors.add("size",new ActionError("error.file.size"));
saveErrors(request,errors);
return (new ActionForward(mapping.getInput()));
}
//*************要用到的输入输出流*****************
InputStream streamIn=file.getInputStream();
OutputStream streamOut=new FileOutputStream(url);
//*************将文件输出到目标文件*****************
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();
file.destroy();
return mapping.findForward("sucess");
}
}
5:properties文件内容:
Xml代码
error.file.size=The file is too large,the size must less than 2M !
error.file.null=Please choose the file!
error.file.type=Type of the file must be ".jpg" or ".jpeg" or ".bmp" or ".gif" !
6:struts-config.xml代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
<form-beans >
<form-bean name="uploadForm" type="testfile.forms.UploadFileForm" />
</form-beans>
<global-forwards>
<forward name="sucess" path="/sucess.jsp" />
<forward name="index" path="/uploadfile.jsp" />
</global-forwards>
<action-mappings >
<action path="/uploadfile"
name="uploadForm"
scope="request"
input="/uploadfile.jsp"
type="testfile.actions.UploadFileAction" />
</action-mappings>
<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>
7:web.xml代码
Xml代码
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>uploadfile.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
<taglib-location>/WEB-INF/struts-html.tld</taglib-location>
</taglib>
</web-app>