Attempting to build a web server from scratch. It's working for html, and other plain text files. Tested in Firefox and Chrome. But I'm having difficulty getting images to display properly. Status 200 returned, in Firefox I get the attached image on request. Other than the response header, do I need to handle image filetypes differently with the printstream?
FileInputStream fileIn = new FileInputStream("test/" +
file);
// split specified file path
String[] pathTokens = tokens[1].split("/|\\.");
String fileExt = pathTokens[tokens.length - 1];
// build response
out.println("HTTP/1.1 200 OK");
if(fileExt.equals("jpg") || fileExt.equals("jpeg") ||fileExt.equals("png") ||
fileExt.equals("ico"))
out.println("Content type: image/" + fileExt);
else
out.print("Content type: text/");
if(fileExt.equals("html"))
out.println(fileExt);
else
out.println("plain");
long size = fileIn.getChannel().size();
out.println("Content-Length: " + Long.toString(size));
out.println("Connect: Close");
out.println("");
int read = 0;
byte[] buffer = new byte[1024];
while ((read = fileIn.read(buffer)) != -1){
out.write(buffer, 0, read);
}
If any further information is needed, please request. I'm more than willing to provide any additional details, or answer any questions I can.
EDIT: Upon further examination I'm actually getting 404 in Firefox, and I'm not really sure what Chrome is, the page displayed is "This site cannot be reached...", but it appears I'm getting 200 returned.
I think I can see a bug:
if(fileExt.equals("jpg") || fileExt.equals("jpeg") ||fileExt.equals("png") ||
fileExt.equals("ico"))
out.println("Content type: image/" + fileExt);
else
out.print("Content type: text/");
if(fileExt.equals("html"))
out.println(fileExt);
else
out.println("plain");
If I re-indent and insert {}'s where the Java compiler thinks they would be.
if (fileExt.equals("jpg") || fileExt.equals("jpeg") ||
fileExt.equals("png") || fileExt.equals("ico")) {
out.println("Content type: image/" + fileExt);
} else {
out.print("Content type: text/");
}
if (fileExt.equals("html")) {
out.println(fileExt);
} else {
out.println("plain");
}
See the problem? If the extension is (say) "jpg", you will get a spurious "plain" line added to the header.
I think you actually meant to write this:
if (fileExt.equals("jpg") || fileExt.equals("jpeg") ||
fileExt.equals("png") || fileExt.equals("ico")) {
out.println("Content type: image/" + fileExt);
} else {
out.print("Content type: text/");
if (fileExt.equals("html")) {
out.println(fileExt);
} else {
out.println("plain");
}
}
This illustrates: