Uploading a File Using html:file


Uploading a File Using <html:file>

This section provides information on the following tag:

  • <html:file> ” Render an HTML <input type=file> element to support file uploading from forms

If you point your browser to the URL

 http://myAppServer/StrutsTaglibs/html.jsp 

you'll bring up the main page that links to all the sample codes for the Struts tag chapters. This section uses the <html:file> Sample Code page at /StrutsTaglibs/HtmlFile.do .

The input form page for this application is very basic and is presented in Figure 12.8.

Figure 12.8. The <html:file> Sample Code page showing a file upload form at /StrutsTaglibs/HtmlFile.do .

graphics/12fig08.gif

Listing 12.10 is the JSP file that creates this page.

Listing 12.10 JSP File Demonstrating Use of the <html:file> Tag for Uploading a File ( HtmlFile.jsp )
 <%@ page language="java" %> <%@ page import="org.apache.struts.action.*" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> <html:html> <head> <title>&lt;html:file&gt; sample code</title> </head> <body bgcolor="white"> <h1>&lt;html:file&gt; sample code</h1> <!--         The most important part is to declare your form's enctype         to be "multipart/form-data", and to have an html:file         element that maps to your ActionForm's FormFile property --> <html:form action="HtmlFile.do" enctype="multipart/form-data">         Please select the file that you would like to upload:<br />         <html:file property="file" /><br /><br />         <html:submit /> </html:form> <p> <logic:notEmpty name="HtmlFileForm" property="fname" >     The file just uploaded was:<p>     <ul>       <li>Name =<bean:write name="HtmlFileForm" property="fname" />       <li>Size =<bean:write name="HtmlFileForm" property="size" />     </ul> </logic:notEmpty> </body> </html:html> 

Reviewing the form bean for this example is valuable to help demonstrate how the <html:file> tag is handled during form processing. Listing 12.11 is the form bean that goes with this JSP file ( HtmlFileForm.java ).

Listing 12.11 Form Bean That Corresponds with HtmlFile.jsp ( HtmlFileForm.java )
 package ch12; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; import org.apache.struts.upload.MultipartRequestHandler; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; /**  * <p>Title: HtmlFileForm.java </p>  * <p>Description: Form Bean for the &lt;html:file&gt; example</p>  * <p>Copyright: Copyright (c) 2002</p>  * @author Kevin Bedell & James Turner  * @version 1.0  *  */ public class HtmlFileForm extends ActionForm {     // Default bean constructor     public HtmlFileForm() { }     /**      * The file that the user has uploaded      */     private FormFile file;     public FormFile getFile() { return this.file; }     public void setFile(FormFile file) { this.file = file; }     /**      * The name of the file - only for displaying results      */     private String fname;     public String getFname() { return this.fname; }     public void setFname(String fname) { this.fname = fname; }     /**      * The size of the file - only for displaying results      */     private String size;     public String getSize() { return this.size; }     public void setSize(String size) { this.size = size; } } 

The processing logic for this form bean is described in the following sections.

For the <html:file> tag, the processing in the Action class is also important. Listing 12.12 is the Action class for this example ( HtmlFileAction.java ).

Listing 12.12 Action Class That Corresponds with HtmlFile.jsp ( HtmlFileAction.java )
 package ch12; import java.io.InputStream; import java.io.IOException; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ForwardingActionForward; import org.apache.struts.upload.FormFile; import org.apache.struts.util.MessageResources; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /**  * Action class to demonstrate handling a <html:file> tag  *  * @author Kevin Bedell & James Turner  * @version 1.0  */ public class HtmlFileAction extends Action {     public ActionForward execute(ActionMapping mapping,                                  ActionForm form,                                  HttpServletRequest request,                                  HttpServletResponse response)     throws Exception {         MessageResources messages = getResources(request);         String dir = messages.getMessage("save.dir");         HtmlFileForm hff = (HtmlFileForm) form;         // org.apache.struts.upload.FormFile contains the uploaded file         FormFile file = hff.getFile();         // If no file was uploaded (e.g. first form load), then display View         if (file == null ) {                 return mapping.findForward("default");         }         // Get the name and file size         String fname = file.getFileName();         String size = Integer.toString(file.getFileSize()) + " bytes";         InputStream streamIn = file.getInputStream();         OutputStream streamOut = new FileOutputStream(dir + fname);         int bytesRead = 0;         byte[] buffer = new byte[8192];         while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {             streamOut.write(buffer, 0, bytesRead);         }         streamOut.close();         streamIn.close();         // Populate the form bean with the results for display in the View         hff.setFname(fname);         hff.setSize(size);         // Clean up our toys when done playing         file.destroy();         // Forward to default display         return mapping.findForward("default");     } } 

The important points from this Action class are covered in the following sections.

The <html:file> Tag

The <html:file> tag provides a method for building applications in which uploading files is a requirement. This tag provides a great deal of flexibility in terms of the file uploading process, naming and storing of files, and so on.

The biggest advantage this tag provides is how much it simplifies handling the uploading of files after you understand the material in this section.

In addition to the example we defined here, additional attributes are available for this tag that can limit the size of the file upload that's accepted (the maxlength attribute) and that indicate to the client browser the content types you can accept (the accept attribute).

Using the <html:file> Tag in the JSP File

Using the <html:file> tag in a JSP file is straightforward. Here's the code from our sample application:

 <html:form action="HtmlFile.do" enctype="multipart/form-data">         Please select the file that you would like to upload:<br />         <html:file property="file" /><br /><br />         <html:submit /> </html:form> 

Two pieces of information in this short listing are important. They are the following:

  • The encoding type on the <html:form> tag must be set to enctype= "multipart/form-data" .

  • The <html:file> tag itself must specify the property file of the form bean that the file is to be stored in. The code that supports this in the form bean is discussed in the next section.

Specifying a Private FormFile Property in the Form Bean

To support the tag we specified in our JSP file, <html:file property="file" /> , there must be a property named file in the form bean. This property must be of type org.apache.struts.upload.FormFile . This is taken care of in our form bean by the following two code snippets:

 import org.apache.struts.upload.FormFile; 

and

 /**  * The file that the user has uploaded  */ private FormFile file; public FormFile getFile() { return this.file; } public void setFile(FormFile file) { this.file = file; } 

These lines in the form bean are all we need to support file uploading.

Processing the File Upload in the Action Class

A file is actually uploaded as a multipart request and is a bit more complex than a normal HTTP form posting. Fortunately, the Struts framework takes care of the hard parts for you. To handle actually uploading and saving the file, we use the following code snippet:

 // Get the name and file size String fname       = file.getFileName(); String size        = Integer.toString(file.getFileSize()) + " bytes"; InputStream streamIn = file.getInputStream(); OutputStream streamOut = new FileOutputStream(dir + fname); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {     streamOut.write(buffer, 0, bytesRead); } streamOut.close(); streamIn.close(); 

At a high level, this code simply defines an InputStream for reading the file contents as they're uploaded and an OutputStream to write the uploaded data to the file system. The code then loops , reading in data and writing it to a file, until there's no more data to read in (that is, the file upload is complete).



Struts Kick Start
Struts Kick Start
ISBN: 0672324725
EAN: 2147483647
Year: 2002
Pages: 177

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net