Display image from web server in C

有些话、适合烂在心里 提交于 2019-12-13 06:59:37

问题


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?


回答1:


The errors are probably creeping in during the fgets. fgets is useful for reading text, but not so much for binary data. Use fread 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, use stat or fstat.



来源:https://stackoverflow.com/questions/28763469/display-image-from-web-server-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!