1.上传文件的jsp文件代码
<%@ 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>
2.ActionForm类代码
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;
}
}
3.Action类的代码
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");
}
}
本文介绍了一个简单的文件上传示例,包括使用JSP实现的文件上传界面、ActionForm类中的文件验证逻辑以及Action类中的文件处理过程。该示例还包含了对上传文件类型和大小的限制。
830

被折叠的 条评论
为什么被折叠?



