我有一个直接写入输出流的动作。有时我会得到以下错误:
Error processing GroovyPageView: getOutputStream() has already been called for this response
Caused by getOutputStream() has already been called for this response
和这一个:
Executing action [getImage] of controller [buddyis.ItemController] caused exception: Runtime error executing action
Caused by Broken pipe
我该如何解决这些问题?我使用的动作如下所示。
注意:如果这很重要,我使用Tomcat 7.0.42!
def getImage() {
byte [] imageByteArray = // some image bytes
response.setHeader 'Content-disposition', "attachment; filename=\"${imageName}${imageExtension}\""
response.setContentType("image/pjpeg; charset=UTF-8")
response.contentLength = imageByteArray.size()
response.outputStream.write(imageByteArray)
response.outputStream.flush()
response.outputStream.close()
return
}
答案 0 :(得分:6)
我不知道你为什么会收到这个错误,但是我每次都会这样做。
我不会致电.flush()
或.close()
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=\"${name}\"")
response.setContentLength(imageByteArray.size())
response.outputStream << imageByteArray
使用上面的工作正常,直到我发现用户可以取消下载,这导致异常。这是我使用的完整代码,而不是response.outputStream << imageByteArray
:
def outputStream = null
try {
outputStream = response.outputStream
outputStream << imageByteArray
} catch (IOException e){
log.debug('Canceled download?', e)
} finally {
if (outputStream != null){
try {
outputStream.close()
} catch (IOException e) {
log.debug('Exception on close', e)
}
}
}