views:

949

answers:

3

hi,

I am new to grails.I am doing web application that uploads the image from client side and it stores that in server.

My Gsp code is:

<g:uploadForm action="saveImage">
<input type="file" name="image"> 
<input type="submit" value="Submit">
</g:uploadForm>

My saveImage action in controller is:

def saveImage={
def file = request.getFile('image')
        if (file && !file.empty) {
            file.transferTo(new java.io.File("image.jpg"))
            flash.message = 'Image uploaded'
            redirect(action: 'uploadImage')
        }
}

In this code if i upload some other files like text files it throws Exception.For that i want to check the file Extension and I want to use If loop that ensures the uploaded file is image file or not.But i dont know how to find the file extension in grails.

Is there any other way to upload images in grails application.It has to accept only image files.

can anyone provide help?

thanks.

+1  A: 

Try this link link text

Warrior
+5  A: 

I dont know the following answer is a right way to find the extension of the file.I am also new to this.But this answer is working

Use file.getOriginalFilename() method.It returns a string like "test.jpg".Then you split the filename using tokenize method by ".".Then you take the last string element from the splitted list.That is extension of the file.Now you can do the remaining process.

+3  A: 

Getting file extension from file.getOriginalFilename() works good.I think that is the better way.