Recipe7.10.Allowing Users to Upload Files


Recipe 7.10. Allowing Users to Upload Files

Problem

You need to allow users to upload file content to a web application.

Solution

Create an ActionForm that uses the Struts FormFile object as a property as shown in Example 7-10.

Example 7-10. ActionForm with FormFile property
package com.oreilly.strutsckbk.ch04; import org.apache.struts.action.ActionForm; import org.apache.struts.upload.FormFile; public class UploadForm extends ActionForm {     private FormFile content;     public FormFile getContent( ) {         return content;     }     public void setContent(FormFile content) {         this.content = content;     } }

Then use the html:file tag on the JSP page (upload_test.jsp) that contains the form as shown in Example 7-11. For file uploads, the enctype attribute of the html:form tag must be set to multipart/form-data and the method attribute set to POST.

Example 7-11. JSP for file upload
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html" %>   <html> <head>   <title>Struts Cookbook - Chapter 4 : Upload Test</title> </head> <body>   <html:form action="/ProcessUpload"              method="POST"             enctype="multipart/form-data">      <html:file property="content"/>     <html:submit/>   </html:form> </body> </html>

The default value for the method attribute of the html:form tag is POST, so the attribute isn't required here. In this case, however, explicitly setting the value reduces the risk of the method type being changed by another developer.


When the form is processed, use the FormFile object to retrieve the uploaded file content. The ProcessUploadAction shown in Example 7-12 retrieves the file contents in an InputStream and writes this data to a file.

Example 7-12. Action that processes uploaded file
package com.oreilly.strutsckbk.ch04; import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; 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.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; public class ProcessUploadAction extends Action {   public ActionForward execute(ActionMapping mapping,       ActionForm form,       HttpServletRequest request,       HttpServletResponse response) throws Exception {     // Get the form file property from the form     UploadForm uploadForm = (UploadForm) form;             FormFile content = uploadForm.getContent( );     InputStream in = null;     OutputStream out = null;           try {       // Get an input stream on the form file       in = content.getInputStream( );            // Create an output stream to a file       out = new BufferedOutputStream (new FileOutputStream("temp.txt"));            byte[] buffer = new byte[512];       while (in.read(buffer) != -1) {         out.write(buffer);       }     }     finally {       if (out != null) out.close( );       if (in != null) in.close( );               }     return mapping.findForward("success");   } }

Discussion

Handling a file upload for a Java-based web application can be critical and downright intimidating for many developers. Thankfully, Struts provides an API for file uploads that simplifies this task. The API is accessed primarily through a single class (FormFile) you can use as a property on your ActionForm.

You can handle file uploads by using the FormFile class as the type for a property of an ActionForm. On the JSP page that displays the form, use the html:file tag to refer to the FormFile property. The html:file tag generates the HTML that lets a user upload a file:

<input type="file">.

The FormFile object encapsulates the uploaded file. It contains information about the name and type of the uploaded file as well as the actual file contents. The getFileName() method returns the actual filename from the client's machine. This filename may have been keyed in by the user directly, or, more commonly, the filename was set when the user chose the file using the "Browse..." button. Figure 7-2 shows the displayed JSP page after the user picked a file from his local system.

Figure 7-2. File upload page


If you're going to save the uploaded file to the server's filesystem, don't make the mistake of using this filename. The filename and path won't be correct for the server and will probably not be valid for the server's operating system. However, you may want to preserve the filename and other information about the file as metadata. You could include the name of the user that uploaded the file as well as the date and time it was uploaded.

The ProcessUploadAction, shown in Example 7-12, handles the FormFile property. The uploadForm.getContent( ) method returns the FormFile property. The getInputStream( ) method of FormFile returns an input stream for reading the file contents. Data is read from the stream in 512-KB chunks and written using an output stream to the temp.txt file.

So where does this file get saved to when it is written? The answer varies by application server. On Tomcat, the filename is relative to the directory from which Tomcat was started, usually <CATALINA_HOME>/bin. Check your application server's documentation for more information.

See Also

The underlying implementation of the Struts file upload capability is provided by the Jakarta Commons FileUpload project. Details can be found at http://jakarta.apache.org/commons/fileupload/. The API documenaton for the Struts html:file tag can be found online at http://struts.apache.org/userGuide/struts-html.html#file.

The Struts source distribution includes a file upload example, similar to this recipe, contained within the struts-examples sample web application.



    Jakarta Struts Cookbook
    Jakarta Struts Cookbook
    ISBN: 059600771X
    EAN: 2147483647
    Year: 2005
    Pages: 200

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