Saturday, July 18, 2009

Handling File Uploads with EasyWeb4J

Most web applications require handling upload of files. A good example of this is an online shopping application which displays an icon for every product available for online purchase.

EasyWeb4J makes handling file uploads in Java web applications really simple. We'd be building a sample application in this post to demonstrate how it can be done.
  1. Every product has a name and a description.
  2. An icon is associated with every product.
  3. The home page lists the icon, name and the description of all the products currently available.
The completed application would look like this


Download the complete source code for this application.

Create a new EasyWeb4J Hibernate Project as described in the tutorial.

MySQL Script

Edit the newly created project's hibernate.xml and update the DB connection information.

Model

src/main/java/org/upload/models/Product.java

Repository

src/main/java/org/upload/repositories/ProductRepository.java

Add Product View

Unlike normal forms, the encoding of forms involving file fields must be "multipart/form-data".

src/main/webapp/WEB-INF/views/Products/add.jsp

Product List View

An interesting thing to note here is that, we use the URL of an action to retrieve the icon of the corresponding product by passing it the product's ID in each row.

src/main/webapp/WEB-INF/views/Products/index.jsp

Controller

src/main/java/org/upload/controllers/ProductsController.java

Some of the points to note in the controller's implementation are:
  1. updateModel() does not process file fields even if they follow the object.property naming convention and hence need to be processed separately in controllers.
  2. Controllers can directly send output to servlets' response and EasyWeb4J will not try to render a view if the action closes the response. This is exactly how the icon() action works.
As it can be seen, EasyWeb4J makes working with file uploads and streaming back uploaded files extremely simple. :)

0 comments:

Post a Comment