Search code examples
grailsgrails-ormrender

Render file from controller


I'm working on a grails application and struggling with rendering text to a file. Currently I can render the text to the screen with the function below which sits in the controller:

    def generateTemplateSQL(Template templateInstance){

    def result = templatingService.buildTemplateSql(templateInstance)
    render result
  }

Now I want to be able to print the same text to a file and this is what I have below. However the button on the front end that I've created for this function causes a 404 error once pressed. I'm guessing I've got something out of place. Any ideas?

    def writeTemplateSQLToFile(Template templateInstance){

    def result = templatingService.buildTemplateSql(templateInstance)
    render (file: new File(result), fileName: "TemplateSQL.met", contentType: "text/met")
  }

Solution

  • Try this:

    def writeTemplateSQLToFile(Template templateInstance){
    
        def result = templatingService.buildTemplateSql(templateInstance)
    
        response.setHeader("Content-disposition", "filename=TemplateSQL.met")
        response.contentType = 'text/met'
        response.outputStream << result
        response.outputStream.flush()
    }