如何将图像加载到浏览器输出流?

时间:2014-04-29 21:17:39

标签: groovy proxy streaming

我有一个用Groovy编写的小代理服务器,它记住用户的请求,然后在SocketOutputStream中加载原始内容。一切(html,js和css)都很好 - 但是图片。所有二进制内容都从页面中消失。

这是我的代码:

int host = 3128
def address = Inet4Address.getByName("localhost")
def server = new ServerSocket(host, 25, address)
println "Appication strted on $address, $host"

while (true) {
  server.accept() { socket ->
    socket.withStreams {SocketInputStream input, SocketOutputStream output ->
        def reader = input.newReader()

        String buffer = reader.readLine()
        params = buffer.split(' ')
        String url = params[1]

        URL contentUrl = new URL(url)
        //Doing some hard work with requested content

        output.withWriter { writer ->
            writer << new URL(url).openStream()
        }
    }
  }

}

也许有人可以帮助我? 感谢。

1 个答案:

答案 0 :(得分:1)

如果你期待二进制数据,你不应该使用读者和作家......

尝试更换:

    output.withWriter { writer ->
        writer << new URL(url).openStream()
    }

使用

    new URL( url ).withInputStream { uin ->
        uin.eachByte( 4096 ) { buffer, nBytes ->
            output.write( buffer, 0, nBytes )
        }
    }