Thursday, May 28, 2009

Using Grails, Upload and Render file

Lets discuss how can we upload a file and store it in a database, along with that how do we render it on the gsp page. I am taking an example to upload and render the image in this blog, though the code would be same for any other file.

So Lets consider I have a domain class with the name Person

class Person {
.
.
.
bytes[] picture
static constraints = {
picture(size:0..5000000) // to store files upto 5MB approx
}
}

Once we have a field with a byte[] defined in the class then automatically its view is generated with a input tag of file type in html, which returns the MultipartFile object in the controller. MultipartFile provides various useful methods which can be used getBytes(), getSize(), getContentType(), getName() etc.

So as MultipartFile object returs the byte[] which is to be stored in a picture property of a person class, in the save action of the PersonController Lets see how we do it :

person.picture = params.picture
or
person.properties = params

//Now the person object holds the image and lets save it

person.save()

We are done with file uploading. Now to render the image/file, lets have a separate controller in a controller directory, where we would define the action to generate the image:

class ImageController { def defaultAction ='show'

def show= {
//loads the class with a name and assigns obj a new instance created of the same object
def obj = Class.forName("${params.classname}",true,Thread.currentThread().contextClassLoader).newInstance();
def object = obj.get( params.id )
response.setContentType(params.mime)
byte[] image = object."${params.fieldName}"
response.outputStream << image

Now where ever we want to display the image, we can just include the following tag:


<img src="${createLink(controller:'image', id:personInstance.id, params:[fieldName:"picture", classname:'Person'])}" / >


Note : The above code can be dangerous as a hacker can modify the className and feildName in the query string and get the hidden information.
Hope this helped.

~Amit Jain~

amit@intelligrape.com

http://www.IntelliGrape.com/