日期:2014-05-17 浏览次数:20623 次
<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 { @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"); } }
<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>