Struts标签库中的文件上传标签(<html:file>)的使用,利用<html:file>实现文件上传一般分为四步:
第一步:
编写JSP页面,在页面中使用struts标签库提供的标签,至少FORM表单组件相关的标签要使用struts提供的。
示例:
JSP页面中的FORM表单块.
<html:form action="upload.do" method="post" enctype="multipart/form-data"> <table border="0"> <tr> <td>文件上传:</td> <td><html:file property="myFile" /></td> </tr> <tr> </tr> <tr> <td colspan="2" align="center"><html:submit value="上传"/></td> </tr> </table> </html:form>
其中需要注意的:
1.<html:form>中的属性enctype="multipart/form-data"是不可少的。
为什么是必须呢?
表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,设置enctype="multipart/form-data"是上传二进制数据。
2.这里使用到的是struts标签库是“struts-html.tld”,所以在JSP页面中需要导入。
完成了JSP页面的编写后,开始第二步。
第二步:
编写ActionForm。
示例:
继承了ActionForm的Java类.
public class UploadForm extends ActionForm { private FormFile myFile; public FormFile getMyFile() { return myFile; } public void setMyFile(FormFile myFile) { this.myFile = myFile; } }
当中提供了一个org.apache.struts.upload.FormFile类型的变量----myFile。注意这里的myFile命名一般不要随便命名,它一般和上传组件<html:file>的属性property的值保持一致(如果不是一样,那么这里提供的set方法就必须与property值保持“一致”,这里所谓的一致就是说property值与ActionForm提供的get和set方法放在一起一定要满足javabean中的get和set方法的命名规范)。
ActionForm编写完成后,就可以开始第三步了。
第三步:
编写Action。
public class UploadAction extends Action { @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { UploadForm uf = (UploadForm) form; //得到FormFile对象,这个对象把要上传的文件封装成了流的形式, //并且当中还封装了上传文件的一些信息,如文件名字等等。 FormFile myFile = uf.getMyFile(); InputStream in = null; OutputStream out = null; try { //得到上传文件的流,可以通过这个流读取上传文件 in = myFile.getInputStream(); //得到服务器的保存图片的路径 String path = this.servlet.getServletContext().getRealPath( "/upload"); //得到上传文件的名字 String fileName = myFile.getFileName(); out = new FileOutputStream(path + "/" + fileName); byte[] b = new byte[1024]; int length = 0; //开始上传文件,每读取1024个字节,就向服务器指定路径位置写入读取到的字节。 while ((length = in.read(b)) != -1) { out.write(b, 0, length); out.flush(); } } catch (IOException ioe) { ioe.printStackTrace(); } finally { //关闭流 in.close(); out.close(); } return mapping.findForward("success"); } }
Action编写完成就只差最后一步。
第四步:
配置struts-config.xml文件。
<form-beans> <form-bean name="uploadForm" type="com.lovo.struts.form.UploadForm"></form-bean> </form-beans> <action-mappings> <action path="/upload" name="uploadForm" type="com.lovo.struts.action.UploadAction"> <forward name="success" path="/success.jsp"></forward> </action> </action-mappings>
做到这里就大功告成了,这样一来上传文件就变得如此的简单。