简体   繁体   English

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

[英]Sending images over http to browser

I would like to implement a simple web server in java. 我想在java中实现一个简单的Web服务器。 The problem is that images are not correctly rendered on the web browser; 问题是图像未在Web浏览器上正确呈现; all I can see, if I go to localhost:8888/image.png, is a white square with exact width, height and weight. 所有我能看到的,如果我去localhost:8888 / image.png,是一个白色的正方形,具有精确的宽度,高度和重量。 Thank you in advance! 先感谢您! :) :)

Here is the code: 这是代码:

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();
}

EDIT: 编辑:

Unfortunately it returns the same message. 不幸的是,它返回相同的消息。

    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(); 

You are using Write class for rendering the image. 您正在使用Write类来渲染图像。 Use the OutputStream to write the image. 使用OutputStream写入图像。 Images are bytes and always byte based streams should be used to render them. 图像是字节,应始终使用基于字节的流来渲染它们。

If you are converting bytes into String then you must use Base64 encoding. 如果要将字节转换为String则必须使用Base64编码。 And on the client side you can specify the image src similar to this "data:image/png;base64," + imageData . 在客户端,您可以指定图像src类似于"data:image/png;base64," + imageData

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM