I have an action that writes directly to the output stream. Sometimes I get the following to errors:
Error processing GroovyPageView: getOutputStream() has already been called for this response
Caused by getOutputStream() has already been called for this response
and this one:
Executing action [getImage] of controller [buddyis.ItemController] caused exception: Runtime error executing action
Caused by Broken pipe
How can I solve these problems? The action I use is listed below.
NOTE: I use Tomcat 7.0.42, if this is important!
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
}
I don't know why you are getting that error, however here is what I do that works everytime.
I don't call .flush() or .close()
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "filename=\"${name}\"")
response.setContentLength(imageByteArray.size())
response.outputStream << imageByteArray
Using the above it was working fine, until I found out a user can cancel a download, which caused an exception. This is the full code I use instead of 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)
            }
        }
    }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With