Merl's Blog

Images

One of the proudest moments so far has been the ability to present images/gifs/txt in my web server.

Part of the reason why I was struggling to display it at the end was because of how I was able to display information initially.

See my initially way that I was able to send information to the client was through this line of code right here

Response response = handler.handle(Request.fromString(requestString));
writer.println(response);

The important line is the last one where I used the print line to pass my information.

Looking back it is silly to not see that this could be a problem when I would want to display a file.

The phase I had to get through first was if I was looking at the right file and how would i transfer that information through.

if (contentType.startsWith("image") || contentType.startsWith("application")) {
   byte[] byteBody;
   try {
       byteBody = Files.readAllBytes(file.toPath());
   } catch (IOException e) {
       throw new RuntimeException(e);
   }
   return new Response(200, byteBody, contentType);
}

The other part I had to do is have different constructors for Response, so I could place either an image like this or a txt body. I only provided the code for the image byte copying.

After passing it through to the correct places, I had to finally send it back to the client.

This next code does have the HTTP message already included in oStream. This code is to decide whether the response has an image or is a text file.

And Finally I found what I needed to write to send out the image to the client. Flush!

if (response.byteBody != null) {
   oStream.write(response.byteBody);
} else if (response.body != null) {
   oStream.write(response.body.getBytes(StandardCharsets.UTF_8));
}
oStream.flush();

Little by little.

Best,

Merl