Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error processing GroovyPageView: getOutputStream() has already been called for this response

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
}
like image 949
confile Avatar asked Aug 06 '13 19:08

confile


1 Answers

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)
            }
        }
    }
like image 167
James Kleeh Avatar answered Oct 09 '22 13:10

James Kleeh