Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get bytes (byte[]) from an uploaded file in Grails

I have a upload form like this (form.gsp):

<html>
<head>
    <title>Upload Image</title>
    <meta name="layout" content="main" />
</head>
    <body>  
        <g:uploadForm action ="upload">
            Photo: <input name="photos" type="file" />
            <g:submitButton name="upload" value="Upload" />
        </g:uploadForm>
    </body>
</html>

I expect the user to upload any picture, and when he clicks on the upload button, I need some way to get the image in my controller action and passed it to the view :

def upload = { 
        byte[] photo = params.photos
            //other code goes here . . . .
    }

This throws an error :

Cannot cast object 'org.springframework.web.multipart.commons.CommonsMultipartFile@1b40272' with class 'org.springframework.web.multipart.commons.CommonsMultipartFile' to class 'byte'

Note that I don't want these photos to be saved on my DB. Actually once the upload action is done, I will process with that image and show the output in upload view itself. So it will be good if I have a solution for it.

Thanks in advance.

like image 437
Ant's Avatar asked Jan 24 '12 08:01

Ant's


1 Answers

def reqFile = request.getFile("photos")
InputStream file = reqFile.inputStream
byte[] bytes = file.bytes

Edit: changed the getBytes to bytes as suggested and as is a better groovy way :)

like image 57
Jan Wikholm Avatar answered Nov 17 '22 04:11

Jan Wikholm