Saturday, March 20, 2010

Java Servlet (3.0): How can I access multipart encoded content provided by a http post request?

At the last friday i stood right before a tricky problem: How can I save a image provided via HTTP post into a database?
I had three problems:
1. How to upload a file via HTML?
2. How to access the data at the server side?
3. How to put in the database using JPA?

The first one was easy, just create a html form add a input field (type='file') and a submit button.

The second one cost me one day. And it was really simple: Just place the @MultipartConfig annotation at the class definition of the servlet and use HTTPRequest.getPart[s]() methods to access the data as an inputstream.

The last part was straight forward: use a InputStreamReader to copy the data into a byte[] and add @Lob byte[] field to the entity class.

Because I use MySQL it was necessary to change the columnt type from TEXT to MEDIUMBLOB.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.