5

我有一个直接写入输出流的操作。有时我会得到以下错误:

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
}
4

2 回答 2

7

我不知道您为什么会收到该错误,但是这是我每次都有效的方法。

我不打电话.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)
            }
        }
    }
于 2013-08-06T20:02:30.543 回答
0

我在 tomcat:7.0.55.3 上运行 grails 2.5 并安装了 java-melody grails 插件时遇到了这个问题。卸载java-melody后它工作得很好

于 2016-04-09T18:16:00.687 回答