Search code examples
grailsfile-uploaduploadgsp

Why can't I find my uploaded file in Grails


I am still new to Grails. I have an app that has a file upload. I have added this to the controller

def upload = {
    def f = request.getFile('myFile')
    if(!f.empty) {
        f.transferTo( new File("${f.name}") )
        response.sendError(200,'Done');
    } else {
        flash.message = 'file cannot be empty'
        render(view:'uploadForm')
    }
}

and this is in _forms.gsp

<div class="fieldcontain ${hasErrors(bean: reportInstance, field: 'myFile', 'error')} ">
    <label for="myFile">
        <g:uploadForm action="upload">
            <input type="file" name="myFile"/>
            <input type= "submit" value="Upload"/>
        </g:uploadForm>
    </label>

When I use a g:link to try to retrieve the upload I get redirected and there is nothing displayed

Any advice would be greatly appreciated g:link I am using

<g:link controller ="Report"
    action="listByUserCompany"
    >Show first ten ordered by Title</g:link>

Solution

  • class UploadController {
    
    def index() { }
    
    def fileupload () {
        def f = request.getFile('myFile')
        if(!f.empty) {
          f.transferTo( new File("${f.name}") )
          render(view:'upload')
        }
        else {
           flash.message = 'file cannot be empty'
           render(view:'upload')
        }
      }
    }
    
    <body>
        <g:uploadForm name="myUpload" action="fileupload" controller="upload">
          <input type="file" name="myFile" />
          <input type= "submit" value="Upload"/>
        </g:uploadForm>
    </body>
    

    i used the above code in my controller and gsp and i made a view named upload in view->upload->upload.gsp .My file uploaded success fully in the root directory of the project itself with name myfile