Struts 1.XX <html:file>的使用
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>
public class UploadForm extends ActionForm {private FormFile myFile;public FormFile getMyFile() {return myFile;}public void setMyFile(FormFile myFile) {this.myFile = myFile;}}
public class UploadAction extends Action {@Overridepublic 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");}}
<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>