My problem is that I am not able to get non-text files to display properly in the browser. In the code for my server, I use a while loop to listen for requests. When a request comes in, I read the headers into a variable headers
. After that, I check if the request is a GET request. If it is, then I check that the file exists and that it is a file and not a directory. Then, I look at the extension of the file to determine the next line in my HTTP response.
pw.print("HTTP/1.1 Status: 200 OK\r\n");
String ext = file.getName().substring( file.getName().lastIndexOf('.') + 1, file.getName().length() );
if(ext.equals("txt"))
{
pw.print("Content-Type: text/plain\r\n\r\n");
}
else if(ext.equals("html"))
{
pw.print("Content-Type: text/html\r\n\r\n");
}
else if(ext.equals("jpg"))
{
pw.print("Content-Type: image/jpeg\r\n\r\n");
}
else if(ext.equals("png"))
{
pw.print("Content-Type: image/png\r\n\r\n");
}
else if(ext.equals("pdf"))
{
pw.print("Content-Type: application/pdf\r\n\r\n");
}
if( !ext.equals("txt") && !ext.equals("html") )
{
ImageInputStream imageStream = ImageIO.createImageInputStream(file);
BufferedImage bufferedImage = ImageIO.read(file);
ImageIO.write(bufferedImage, ext, socket.getOutputStream());
}
Now, as far as I know once I get into the last conditional (I'm requesting localhost:port/my_png.png
) then the content should be written to the socket and, because I told it what its Content-Type
should be, the browser should be able to interpret that file. Unfortunately, that is not happening. I am getting text output in the browser that are bytes. My output looks something like this:
‰PNG
���
IHDR���i���`���‘ïË¥��%IDATxÚíœ=h#×úÆ]ÜBE
Does anyone know why I'm having this problem?