jsp文件代码:
<%@ page language="java" pageEncoding="GB2312"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html>
<head>
<title>HTML Tags</title>
</head>
<body>
<html:form action="/upload" method="POST" enctype="multipart/form-data">
<html:file property="file"></html:file>
<html:submit/> <html:cancel/>
</html:form>
</body>
</html>
有以下几点需要注意:
1: <html:file>必须嵌套在<html:form>标签中。
2:<html:form>标签的method的属性必须设为"post".
3:<html:form>标签的编码类型enctype属性必须为"multipart/form-data"。
4:<html:file>标签必须设为property属性,这个属性和ActionForm Bean中FormFile类型的属性对应。
UploadForm.java文件部分代码:
private FormFile file;
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.file = null;
}
public void setFile(FormFile file) {
this.file = file;
}
public FormFile getFile() {
return file;
}
UploadAction.java文件部分代码:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws IOException {
UploadForm uploadForm = (UploadForm) form;
FormFile file = uploadForm.getFile();
if(file != null){
String strFileName = file.getFileName();
MessageResources mr = getResources(request);
String strFilePath= mr.getMessage("FilePath");//获取资源文件中设置的路径
try{
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(strFilePath + "/" + strFileName);
int byteRead = 0;
byte[] buffer = new byte[8192];
while((byteRead=is.read(buffer,0,8192)) != -1){
os.write(buffer,0,byteRead);
}
os.close();
is.close();
file.destroy();
}catch(Exception e){
...
}
说明:在资源文件中设置了FilePath = D:/Program Files,在此把要上传的路径从资源文件中获取出来,如果要上传到系统当前运行的某个目录中的话可以通过以下方式来获取系统当前的路径:
request.getSession().getServletContext().getRealPath("/");
该方法同request.getRealPath("/")一样都可以获取当前系统的路径,不过request.getRealPath("/")的方法已经不推荐使用。