0

我想用java实现一个简单的Web服务器。问题是图像没有在网络浏览器上正确呈现;如果我访问 localhost:8888/image.png,我所能看到的只是一个具有精确宽度、高度和重量的白色方块。先感谢您!:)

这是代码:

public Http(Socket server) throws IOException {
    in = new BufferedReader(new InputStreamReader(server.getInputStream()));
    parseHeader(in);
    String response = new String();
    out = new PrintWriter(server.getOutputStream(), true);
    Files f = new Files(getHomePath() + httpRequestedPage);

    if(!f.exists) {
        // 404 ERROR
    } else {
            response += "HTTP/1.1 200 OK\r\n";
            response += "Date: " + nowDate + "\r\n";
            response += "Content-Type: image/png\r\n";
            response += "Content-Length: " + res.length() + "\r\n";
            response += "Connection: keep-alive\r\n";
            response += "\r\n";
            response +=  IOUtils.toString(new FileInputStream(getHomePath() + httpRequestedPage));
    }

    out.println(response);
    in.close();
    out.close();
}

编辑:

不幸的是,它返回相同的消息。

    out = new PrintWriter(server.getOutputStream(), true);

    OutputStream out2 = server.getOutputStream(); 
    File file = new File(HttpServer.getHomePath() + httpRequestedPage);
    InputStream stream = new FileInputStream(file); 


    String response = new String();
    response += "HTTP/1.1 200 OK\r\n";
    response += "Date: " + nowDate + "\r\n";
    response += "Content-Type: image/png\r\n";
    response += "Content-Length: " + file.length() + "\r\n";
    response += "Connection: keep-alive\r\n";
    response += "\r\n";
    out.println(response);
    IOUtils.copy(stream, out2); 
    out.close();
    out2.close(); 
4

2 回答 2

2

您正在使用 Write 类来渲染图像。使用 OutputStream 写入图像。图像是字节,应该使用基于字节的流来渲染它们。

于 2013-03-27T17:25:29.553 回答
0

如果要将字节转换为String,则必须使用Base64编码。在客户端,您可以指定与src此类似的图像"data:image/png;base64," + imageData

于 2013-03-27T17:48:35.667 回答