I am coding a web server on C. I am able to view HTML and txt files however I am unable to view image files.
All I get is a error "The image “http://localhost:8080/images/image.jpg” cannot be displayed because it contains errors."
if(strstr(method, "GET") != NULL)
{
f = fopen(url+1, "rb");
if(f != NULL)
{
strncat(response, "HTTP/1.1 200 OK\r\n", 20);
if(strstr(url, ".html") || strstr(url, ".htm"))
{
strncat(response, "Content-Type: text/html\r\n\r\n", 30);
}
else if(strstr(url, ".txt"))
{
strncat(response, "Content-Type: text/plain\r\n\r\n", 30);
}
else if(strstr(url, ".jpg") || strstr(url, ".jpeg"))
{
strncat(response, "Content-Type: image/jpeg\r\n\r\n", 30);
}
filesize = stat(url+1, &st);
filesize = st.st_size;
strncat(response, "Content-Length: 67210\r\n\r\n", 40);
while(fread(text,1 , 1, f))
{
strncat(response, text, filesize);
}
printf("%d\n", strlen(text));
printf("%d\n", strlen(response));
write(client_fd, response, strlen(response)); /*-1:'\0'*/
fclose(f);
}
else
{
write(client_fd, not_found_response, strlen(not_found_response)); /*-1:'\0'*/
}
}
else
{
write(client_fd, bad_request_response, strlen(bad_request_response)); /*-1:'\0'*/
}
close(client_fd);
}
EDIT: I have edited my codes with the suggestions below. However I am still having the same problem. I have checked the filesize and it is 67210 but when I do strlen(response) I only get 66882. I am still missing some could that be the problem?
The errors are probably creeping in during the
fgets
.fgets
is useful for reading text, but not so much for binary data. Usefread
instead, and don't do the silly seek to the end trick to find the size of the data; just read to the end and write the data into the response. To get the size of the file for the header, usestat
orfstat
.