在C中显示来自Web服务器的图像 [英] Display image from web server in C

查看:65
本文介绍了在C中显示来自Web服务器的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C上编码Web服务器.我能够查看HTML和txt文件,但是无法查看图像文件.

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.

我得到的只是一个错误图像" http://localhost:8080/images/image.jpg "无法显示,因为其中包含错误."

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);
}

我已经按照以下建议编辑了代码.但是我仍然有同样的问题.我已经检查了文件大小,它是67210,但是当我做strlen(response)时,我只得到66882.我仍然缺少一些问题吗?

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?

推荐答案

错误可能在 fgets 期间蔓延. fgets 对于读取文本很有用,但对于二进制数据则不是那么有用.请改用 fread ,不要傻乎乎地寻找数据的大小;只需读到最后,然后将数据写入响应中即可.要获取标题文件的大小,请使用 stat fstat .

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.

这篇关于在C中显示来自Web服务器的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆