Upload - Struts-Examples1.3.8
Upload -Struts-Examples1.3.8
l 上傳文件的form定義
<html:form action="upload-submit.do?queryParam=Successful" enctype="multipart/form-data"> <p>Please enter some text, just to demonstrate the handling of text elements as opposed to file elements: <br /> <html:text property="theText" errorStyle="background-color: yellow"/></p> <p>Please select the file that you would like to upload: <br /> <html:file property="theFile" errorStyle="background-color: yellow" /></p> <p>If you would rather write this file to another file, please check here: <br /> <html:checkbox property="writeFile" /></p> <p>If you checked the box to write to a file, please specify the file path here: <br /> <html:text property="filePath" errorStyle="background-color: yellow"/></p> <p> <html:submit /> </p> </html:form> |
l FormBean的定義
<form-beans> <form-bean name="uploadForm" type="org.apache.struts.webapp.upload.UploadForm"/> </form-beans> |
publicclass UploadForm extends ValidatorForm { /** *Thevalueofthetexttheuserhassentasformdata */ protected String theText; /** *Thevalueoftheembeddedquerystringparameter */ protected String queryParam; /** *Whetherornottowritetoafile */ protectedbooleanwriteFile; /** *Thefilethattheuserhasuploaded */ protected FormFile theFile; /** *Thefilepathtowriteto */ protected String filePath; /** *Checktomakesuretheclienthasn'texceededthemaximumalloweduploadsizeinsideofthis validatemethod. */ public ActionErrors validate( ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = super.validate(mapping, request); //has the maximum length been exceeded? Boolean maxLengthExceeded = (Boolean) request.getAttribute( MultipartRequestHandler.ATTRIBUTE_MAX_LENGTH_EXCEEDED); if ((maxLengthExceeded != null) && (maxLengthExceeded.booleanValue())) { if (errors == null) { errors = new ActionErrors(); } errors.add( ActionMessages.GLOBAL_MESSAGE , new ActionMessage("maxLengthExceeded")); errors.add( ActionMessages.GLOBAL_MESSAGE , new ActionMessage("maxLengthExplanation")); } return errors; } } |
ValidatorForm 表示可以允許validate xml進行數據驗證。
<form-validation> <formset> <form name="uploadForm"> <field property="theText" depends="required,minlength"> <arg key="The Text" resource="false" position="0"/> <arg name="minlength" key="${var:minlength}" resource="false" position="1"/> <var> <var-name>minlength</var-name> <var-value>5</var-value> </var> </field> <field property="filePath" depends="validwhen"> <arg key="File Path" resource="false" position="0"/> <var> <var-name>test</var-name> <var-value>((writeFile == "false") or (*this* != null))</var-value> </var> </field> </form> </formset> </form-validation> |
驗證theText字段長度至少5個字符,如果有寫文件標識,那么必填filePath文件路徑名。
l 上傳操作的Action
<action path="/upload-submit" type="org.apache.struts.webapp.upload.UploadAction" name="uploadForm" scope="request" validate="true" input="input"> <forward name="input" path="/upload.jsp"/> <forward name="display" path="/display.jsp"/> </action> |
如果,標識為輸出到其他文件,就把文件上傳到服務器上;
否則,讀取文件內容,然后打印到第二個頁面上。
publicclass UploadAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { if (form instanceof UploadForm) { //this line is here for when the input page is upload-utf8.jsp, //it sets the correct character encoding for the response String encoding = request.getCharacterEncoding(); if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) { response.setContentType("text/html; charset=utf-8"); } UploadForm theForm = (UploadForm) form; //retrieve the text data String text = theForm.getTheText(); //retrieve the query string value String queryValue = theForm.getQueryParam(); //retrieve the file representation FormFile file = theForm.getTheFile(); //retrieve the file name String fileName= file.getFileName(); //retrieve the content type String contentType = file.getContentType(); boolean writeFile = theForm.getWriteFile(); //retrieve the file size String size = (file.getFileSize() + " bytes"); String data = null; try { //retrieve the file data ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream stream = file.getInputStream(); if (!writeFile) { //only write files out that are less than 1MB if (file.getFileSize() < (4*1024000)) { byte[] buffer = newbyte[8192]; int bytesRead = 0; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { baos.write(buffer, 0, bytesRead); } data = new String(baos.toByteArray()); } else { data = new String("The file is greater than 4MB, " + " and has not been written to stream." + " File Size: " + file.getFileSize() + " bytes. This is a" + " limitation of this particular web application, hard-coded" + " in org.apache.struts.webapp.upload.UploadAction"); } } else { //write the file to the file specified OutputStream bos = new FileOutputStream(theForm.getFilePath()); int bytesRead = 0; byte[] buffer = newbyte[8192]; while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.close(); data = "The file has been written to """ + theForm.getFilePath() + """"; } //close the stream stream.close(); } catch (FileNotFoundException fnfe) { returnnull; } catch (IOException ioe) { returnnull; } //place the data into the request for retrieval from display.jsp request.setAttribute("text", text); request.setAttribute("queryValue", queryValue); request.setAttribute("fileName", fileName); request.setAttribute("contentType", contentType); request.setAttribute("size", size); request.setAttribute("data", data); //destroy the temporary file created file.destroy(); //return a forward to display.jsp return mapping.findForward("display"); } //this shouldn't happen in this example returnnull; } } |
l 顯示結果的頁面是一個jsp,讀取request上下文的屬性。
posted on 2008-07-13 18:05 MingIsMe 閱讀(104) 評論(0) 編輯 收藏 所屬分類: 16 案例分析