Reputation: 1
This code loads my html but it will not load my jpgs in the html, when I run the code it seems like it is working and all the bytes are being sent for each image but they do not show up in my browser. Im supposed to use the DataOutputStream to send the bytes but maybe thats the problem? im really lost and brand new to network programming.
public void run(){
System.out.println("CLIENT THREAD STARTING");
String req = "";
if(clientIn.hasNextLine()){
req = clientIn.nextLine();
System.out.println("Header: " + request);
}
PrintWriter toClient = null;
try {
toClient = new PrintWriter(sock.getOutputStream());
} catch (IOException e2) {
e2.printStackTrace();
}
//only sends files if client requests them
if(request.contains("GET")){
req = req.substring(request.indexOf("/") + 1);
String name = req.substring(0, req.indexOf(" "));
String type = "";
if(name.contains(".jpg")){
type = "text/html";
}
else if(name.contains(".html")){
type = "image/jpeg";
}
File theFile = new File(fileName);
FileInputStream fileIn = null;
try{
fileIn = new FileInputStream(fileName);
}catch(FileNotFoundException e){
toClientText.println("404");
toClientText.flush();
System.exit(-1);
}
System.out.println("File name " + name);
toClientText.println("HTTP/1.1 200 OK");
toClientText.println("Connection: closed");
toClientText.println("Content-Length: " + theFile.length());
toClientText.println("Content-Type: " + type);
toClientText.println("\n");
toClientText.flush();
DataOutputStream dataStream = null;
try {
dataStream = new DataOutputStream(sock.getOutputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
byte[] send = new byte[1024] ;
try {
while ((fin.read(send)) != -1 ) {
toClientData.write(send);
toClientData.flush();
}
toClientData.close();
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else{
toClientText.println("Bad Request 400");
toClientText.flush();
}
}
Upvotes: 0
Views: 39
Reputation: 8598
toClientText.println("Content-Type: " + fileType);
toClientText.println("\n");
This will create 3 line breaks between your header and the file data, so your browser will think the third line break is part of the image, which will break the image.
Also, even though all browsers can handle \n
linebreaks, be aware that the standard demands \r\n
linebreaks, not \n
.
This should work:
toClientText.println("Content-Type: " + fileType);
toClientText.println();
Upvotes: 2