将二进制内容直接写入客户端,绕过Grails视图层

kno*_*orv 4 grails

以下操作旨在将bytes完全绕过Grails视图层的二进制内容直接写入客户端:

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

我的印象是return falseGrails会完全跳过视图层.但是,似乎并非如此,因为上面的代码仍然使Grails搜索/WEB-INF/grails-app/views/controllerName/actionName.jsp(由于没有这样的文件存在,因此失败了404).

题:

  • 鉴于上面的代码,我如何完全绕过Grails中的视图层?

Bur*_*ith 7

您应该返回null或者根本不返回任何内容,这被解释为null.以下是来自发送动态生成的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()
}
Run Code Online (Sandbox Code Playgroud)