Reputation: 13
I would like to implement a simple web server in java. The problem is that images are not correctly rendered on the web browser; all I can see, if I go to localhost:8888/image.png, is a white square with exact width, height and weight. 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();
Upvotes: 0
Views: 7643
Reputation: 8598
If you are converting bytes into String
then you must use Base64
encoding. And on the client side you can specify the image src
similar to this "data:image/png;base64," + imageData
.
Upvotes: 0
Reputation: 475
You are using Write class for rendering the image. Use the OutputStream to write the image. Images are bytes and always byte based streams should be used to render them.
Upvotes: 2