通过http将图像发送到浏览器

时间:2013-03-27 17:20:19

标签: java http

我想在java中实现一个简单的Web服务器。 问题是图像未在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(); 

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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