Uploading Files

 < Day Day Up > 



Let's say that you want users to be able to upload a picture of themselves. To do this, you must enable file upload in your Struts application. Of course, you don't want them to upload a 1GB image of themselves, so you have to put some limits on the pictures that users upload.

First, set up two areas for enabling the uploading of files: enable the user to supply the file with an HTML form, and enable the Struts application to process the file upload.

To enable the user to upload a file, set the encoding type of html:form to multipart/form-data and use the html:file tag as follows:

 <html:form action="/UserUpdate"            method="post"            enctype="multipart/form-data">    <html:file property="userImage"/> <br />   ... 

The property userImage in the userForm is of type FormFile (org.apache.struts.upload.FormFile). FormFile represents the file sent by the client. FormFile has a method called getlnputStream, which returns an InputStream. The action handler for this form uses FormFile to access the file:

 public ActionForward execute(ActionMapping mapping,                              ActionForm form,                              HttpServletRequest request,                              HttpServletResponse response) throws Exception {     UserForm userForm = (UserForm) form;     InputStream inputStream =          userForm.getUserImage().getInputStream();     // Do something with the inputStream, it is the file data.     ...   } 

To set up the Struts application to restrict file size and to specify the directory location, you could set up a controller element:

   <controller maxFileSize="200K" tempDir="/temp/struts/user/uploads/"/> 

This code snippet states that the temporary files will be put into a directory provided by your servlet container in the directory /temp/struts/user/uploads/ and that users are allowed to upload files up to 200KB only. You can also specify the size of the input buffer and other parameters; see Chapter 15, "The struts-config.xml File," for more details.

At eBlox, we allowed users to upload product data using this Struts feature. When you compare this code to the way we used to have to do it, you can easily see that the Struts approach is much easier than the alternatives.



 < Day Day Up > 



Professional Jakarta Struts
Professional Jakarta Struts (Programmer to Programmer)
ISBN: 0764544373
EAN: 2147483647
Year: 2003
Pages: 183

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