leke
leke

Reputation: 155

How to save uploaded image

I'm wondering how I could save an uploaded image in grails.

The situation: I have a gsp page with a form, containing a file upload. I tried to get the data from the fileupload, but it just won't work.

In the controller:

    def file = request.getFile('fileupload')
    appearanceInstance.logo = file.encodeAsBase64().toString()

In the view:

     <g:form action="save" enctype="multipart/form-data">
                <div class="file-upload">
                    <label >Choose logo</label>
                    <input id="fileupload" type="file" name="fileupload" onchange="handleFileSelect(this)"/>
                </div><br/>
                <br/>
     </g:form>

Anyone who had experience with this?

this might be another way to do it, but since I adapt an in the view when an image is selected using the file upoad, can I get the image data from the in the controller?

Thanks in advance!

UPDATE:

to be clear, there are some other controls in the form, from which I get the other parameters to save.

Upvotes: 1

Views: 6742

Answers (3)

justice
justice

Reputation: 306

try this i hope this will help you it works for me also see this post

Class SomeController{
  def uploader(){

  }
  def save(){
     String s=""
     CommonsMultipartFile f=request.getFile('fileupload')
     final String name =f.getOriginalFilename()
     def fos= new FileOutputStream(new File(name))
     f.getBytes().each{ fos.write(it) }
     s=Base64.encode(f.getBytes())
        fos.flush()
        fos.close()
    render 'done now refresh your source directory to see the file ${s}'
}

and the view 'uploader.gsp'

<g:form action="save" enctype="multipart/form-data">
        <div class="file-upload">
            <label>Choose logo</label> <input id="fileupload" type="file"
                name="fileupload" />
        </div>
        <input type="submit" class="buttons" value="Upload" />
    </g:form>

Upvotes: 1

Mr. Cat
Mr. Cat

Reputation: 3552

I guess this example Simple Avatar Uploader will answer all your questions

Upvotes: 3

user1033237
user1033237

Reputation: 14

Hi try with this one .

def save = {

def requestInstance = new Request(params)
def requestNumberInstance = new RequestNumber()

if(requestInstance.validate() && requestInstance.save(flush: true)){
    println "Saved successfully with ${requestInstance.picture1.length} bytes"
} 
else {
    println "Save failed"
}

Upvotes: 0

Related Questions