<script type="text/javascript">
function subForm()
{
var str = document.FileUploadForm.file.value;
var str2 = str.split(".");
var str3 = str2[str2.length-1];
if(str3.toUpperCase()=='JPG'||str3.toUpperCase()=='GIF')
{
return true;
}else
{
alert('上传文件类型不对!');
return false;
}
}
</script>
</head>
<body>
<html:form action="/FileUpload" enctype="multipart/form-data" οnsubmit="return subForm()">
选择上传的文件:<html:file property="file"></html:file><br/>
<html:submit></html:submit>
</html:form>
</body>
</html:html>
form bean 文件:FileUploadForm
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.bluedot.web.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.upload.FormFile;
public class FileUploadForm extends ActionForm {
private FormFile file;
public FormFile getFile() {
return file;
}
public void setFile(FormFile file) {
this.file = file;
}
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.file = null;
}
}
FileUploadAction
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.bluedot.web.actions;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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 com.bluedot.web.forms.FileUploadForm;
public class FileUploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
FileUploadForm f = (FileUploadForm)form;
FormFile file = f.getFile();
byte[] result = null;
String path = "/upload/"+file.getFileName();
String realpath =getServlet().getServletContext().getRealPath(path);
try {
result = file.getFileData();
File aa = new File(realpath);
if(!aa.exists())
{
aa.createNewFile();
}
FileOutputStream fos = new FileOutputStream(aa);
fos.write(result);
return mapping.findForward("fileok");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return mapping.findForward("error");
}
}
}