Uploading Files

It's quite easy to upload files using Spring. You can choose between the Jakarta Commons FileUpload package (http://jakarta.apache.org/commons/fileupload) and the O'Reilly Servlet (COS) package (http://servlets.com/cos/index.html) where the latter can be used under the terms of the Buy-A-Book license. (Be sure to read and understand the terms of that license before using COS.) Whichever package you will be using, accessing files uploaded using a browser is done in a consistent way; the only difference between the two is the way the so-called multipart resolver is configured in your application context. The resolver detects whether an incoming request is a multipart request containing uploaded files, and, if so, Spring wraps the complete HttpServletRequest in a MultipartHttpServletRequest offering methods to retrieve the uploaded data.

This consistent approach is ensured through the org.springframework.web.multipart.MultipartResolver interface, which is implemented for both these third-party frameworks and could equally be implemented to work with any other technology for multipart handling.

Configuring the Multipart Resolver

Two multipart resolvers exist: one based on the COS package and another one based on Commons FileUpload. Both resolvers have properties you can modify to customize the resolver's behavior. Those properties include the limit of the file size that can be uploaded and the temporary storage location. More information on which parameters are available can be found in the Spring JavaDoc.

The following code snippets show how to configure both the multipart resolver that uses Commons FileUpload and the one that uses COS:

 <bean >   <!-- maximum file size (1 megabyte) -->   <property name="maxUploadSize"><value>1048576</value></property> </bean>      <bean >   <property name="maxUploadSize"><value>1048576</value></property> </bean> 

You do not need to worry about wiring the resolver to controllers or the dispatcher servlet; Spring automatically detects it and will start using it to inspect requests immediately.

Creating a Form to Upload a File

File can be uploaded using a form, but there are some special requirements when constructing such a form. First of all you need to include an <input type="file"> element and you also need to specify the encoding of the form in which you include the input element. A complete example:

 <form method="post" enctype="multipart/form-data">   File: <input type="file" name="file"/> </form> 

This is all you need to do to allow users to upload files using a web browser, although of course you still need to develop a controller that takes care of the data uploaded.

Handling Uploaded Data

There are two ways to retrieve the data that has been uploaded by users. As mentioned previously, Spring automatically wraps the HttpServletRequest in a MultipartHttpServletRequest to allow retrieval of the data. Every controller that has access to the HttpServletRequest can cast it to the latter:

 public class UploadSeatingPlanController extends AbstractController {        protected ModelAndView handleRequestInternal(     HttpServletRequest request, HttpServletResponse response) {          // if uploaded data is available, the request is a MultipartHttpServletRequest     // so let’s check that     if (!(request instanceof MultipartHttpServletRequest)) {       return new ModelAndView("error", "message", "unexpected.noseatingplan");     }          MultipartHttpServletRequest mpRequest = (MultipartHttpServletRequest)request;     // the map containing file names mapped to files     Map m = mpRequest.getFileMap();     // an iterator iterator over all files     Iterator it = mpRequest.getFileNames();          // code that handles the file(s) uploaded   } } 

While it is pretty straightforward, Spring provides an even more elegant way to retrieve the data from the request, almost without any custom code, with the domain model object containing, for example, a byte[] property:

 public class SeatingPlan {   private byte[] file;        public void setFile(byte[] file) {    this.file = file;   }        public byte[] getFile() {     return this.file;   } } 

Using a custom editor, we don't need to cast the request to MultipartHttpServletRequest. Instead, Spring does the binding for us (if, of course, we configure the form controller correctly) and we just have to take care of saving our domain object. Note that an additional editor (the StringMultipartFileEditor) is available to automatically convert the file to a String and bind it to the domain object. Also, you could use the MultipartFile type in your domain object, but this creates an unnecessary dependency to the MultipartFile class and is discouraged.

 public class UploadSeatingPlanController extends SimpleFormController {          protected void initBinder(     HttpServletRequest request,     ServletRequestDataBinder binder)   throws ServletException {          // bind the custom editor that will take care of the uploaded data     binder.registerCustomEditor(byte[].class,      new ByteArrayMultipartFileEditor());   }        protected ModelAndView doSubmitAction(Object sp) {          // Spring has bound the file to the seating plan     SeatingPlan seatingPlan = (SeatingPlan)p;          // do something with the seating plan... e.g. save it!          // and then... return the success view   } } 


Note that the name of the input element (file) in the form described previously corresponds to the name of the property in the domain object.

Professional Java Development with the Spring Framework
Professional Java Development with the Spring Framework
ISBN: 0764574833
EAN: 2147483647
Year: 2003
Pages: 188

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