Writing binary content directly to the client, bypassing the Grails view level

The following action is intended for writing binary bytes directly to the client, completely bypassing the Grails view level:

 def actionName = { byte[] bytes = ... ServletOutputStream out = response.getOutputStream() out.write(bytes) out.flush() out.close() return false } 

I had the impression that return false would force Grails to completely skip the view layer. However, this is not the case, since the above code still forces Grails to look for /WEB-INF/grails-app/views/controllerName/actionName.jsp (which does not work with 404, since such a file does not exist).

Question:

  • Given the code above, how do I get around the view layer in Grails completely?
+4
source share
2 answers

It seems like Grails is trying to display the view if response.contentType.startsWith('text/html') . This seems to be a known bug, see GRAILS-1223 .

Here are two issues:

  • Use render(contentType: "text/html", text: htmlString) as suggested in GRAILS-1223 . This will bypass the presentation level.
  • Clear contents with response.contentType = '' . This will also bypass the presentation layer. However, note that the content will be transmitted to the end user without a Content-Type, which may confuse some browsers.
+2
source

You must return zero or nothing at all, which is interpreted as null. Here is some working code from an action that sends a dynamically generated PDF:

 def pdf = { byte[] content = ... String filename = ... response.contentType = 'application/octet-stream' response.setHeader 'Content-disposition', "attachment; filename=\"$filename\"" response.outputStream << content response.outputStream.flush() } 
+7
source

All Articles