Upload file to grails

I am trying to upload a file to grails in my gsp I have:

<g:form id="update" url="[action: 'updateStatus',]"> <g:textArea name="message" value="" cols="3" rows="1"/><br/> <g:textField id="tagField" name="tag" value=""/><br/> <input id="inputField" type="file" name="myFile" enctype="multipart/form-data" /> <g:submitButton name="Update Status"/> </g:form> 

In my controller, I:

  def updateStatus(String message) { if (params.myFile){ def f = request.getFile('myFile') } 

A request error in a file with this error:

 No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [myFile] 

Any ideas why this is the way I am, and use getFile in my other controllers that work just fine.

+8
input grails
source share
3 answers

here is the submit working file:

form (gsp)

 <form method="post" enctype="multipart/form-data"> <p><input type='file' name="cfile"/></p> <input type='submit'> </form> 

the controller that will store the submitted file in "D: / submitted_file":

 def index() { if(params.cfile){ if(params.cfile instanceof org.springframework.web.multipart.commons.CommonsMultipartFile){ new FileOutputStream('d:/submitted_file').leftShift( params.cfile.getInputStream() ); //params.cfile.transferTo(new File('D:/submitted_file')); }else{ log.error("wrong attachment type [${cfile.getClass()}]"); } } } 

this works for me (grails 2.0.4)

+7
source share

You need enctype="multipart/form-data" in the g:form tag so that the browser uses a multi-page request.

+3
source share

To upload a file, you must install enctype on the form. To do this, you can use <g:uploadForm> , which is identical to the standard form tags, except that it automatically sets the enctype attribute to "multipart / form-data".

I prefer to use the Grails Selfie Plugin plugin to upload images / files to attach files to your domain models, upload to CDN, check contents or create thumbnails.

Domain

 import com.bertramlabs.plugins.selfie.Attachment class Book { String name Attachment photo static attachmentOptions = [ photo: [ styles: [ thumb: [width: 50, height: 50, mode: 'fit'], medium: [width: 250, height: 250, mode: 'scale'] ] ] ] static embedded = ['photo'] //required static constraints = { photo contentType: ['image/jpeg','image/png'], fileSize:1024*1024 // 1mb } } 

Gsp

 <g:uploadForm name="myUpload" controller="upload" action="updateStatus"> <input type="file" name="myFile" /> </g:uploadForm> 

controller

 class PhotoController { def upload() { def photo = new Photo(params) if(!photo.save()) { println "Error Saving! ${photo.errors.allErrors}" } redirect view: "index" } } 

Sources

1. uploadFrom

2. selfie plug

0
source share

All Articles