Monday, July 20, 2009

Saving images as blob in the database using Grails

Handling images is not as easy as handling simple http parameters. This is because images are received as binary objects that you can't directly put in the database field. Here's how i handled saving images to the database:

First, the form containing the image file input field should be declared as multipart:

As i understand it, we need to specify multipart because you can't mix the text parameters with the binary parameters, so we should have it as multipart.

Of course, the file field inside the form should exist, for user to input the image file, e.g.:

<input id="screenshot" name="screenshot" type="file" />

Ok. now, in the controller, say ImageController, we can process the binary image this way:

def record = new Record()
record.properties = params
if(request instanceof MultipartHttpServletRequest) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("screenshot");
record.screenshot = file.bytes // screenshot is the image blob field of the record
}
record.save() // create the record


On save, the record should be created with the image stored as blob.
You might encounter some problem with the image field in the groovy file. So i suggest that you change the field into byte[] instead of Blob. i.e. in Record.groovy above,:

class Record {
// ..
// some fields
// ..
byte[] screenshot // declare the image as byte[] instead of blob
// ..
static constraints = {
// ..
screenshot(maxSize:1073741824) // max 4GB file
}
}


If you don't do the procedure above to your groovy domain class, there might be a problem with saving the image to the blob field in the database.

Next post: how to display an image file from the database to the web page.

No comments:

Post a Comment