如何在C中通过HTTP协议发送图像? [英] How do I send an image over HTTP protocol in C?

查看:262
本文介绍了如何在C中通过HTTP协议发送图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名正在做网络服务器练习的学生,我需要一些帮助.

I'm a student doing a web server exercise and I need a bit of help.

我的Web服务器可以很好地处理文本页面,但是每当浏览器发送---GET /img.jpg HTTP/1.1请求时,我都不知道如何处理它.我听说HTTP协议是基于文本的,那么如何在HTTP响应中发送图像?

I have my web server working fine for text pages but whenever the brower sends a ---GET /img.jpg HTTP/1.1 request, I don't know how to handle it. I've heard the HTTP protocol is text based, so how do I send an image in my HTTP response?

这是我创建常规HTTP响应的部分,我打算使用readresult == 2发出图像信号.

Here is a segment where I create my normal HTTP response, I plan to use readresult == 2 to signal an image.

if(readresult == 1){
    sprintf(toreturn, "%s\r\n%s\r\n%s\r\n\r\n%s", "HTTP/1.1 200 OK", "Content-Type: text/html", "Connection: close", readpagestring);
    returnflag = 1;
}
else if(readresult == 2){
    returnflag = 2;
}
else{
    sprintf(toreturn, "%s\r\n%s\r\n%s\r\n\r\n%s", "HTTP/1.1 404 Not Found", "Content-Type: text/html", "Connection: close", readpagestring);
    returnflag = 0;
}

及其调用的功能

int readpage(char *readaddress, char *pagereturn){
    FILE *inputfile = (FILE *)calloc(1,sizeof(FILE));
    int flag;
    int c;
    int n = 0;
    readaddress++;
    inputfile=fopen(readaddress,"r");
    if (inputfile==NULL){
        FILE *missingfile;
        missingfile=fopen("404.html","r");
        while ((c = fgetc (missingfile)) != EOF){
            *(pagereturn+n) = c;
            n++;
        }
        flag = 0;
        fclose (missingfile);
    }
    else{
        while ((c = fgetc (inputfile)) != EOF){
            *(pagereturn+n) = c;
            n++;
        }
        flag = 1;
        fclose (inputfile);
    }
    return flag;
}

推荐答案

您必须返回这样的HTTP response :(非常小,您仍然可以添加所需的所有标头)

You have to return a HTTP response like this: (very minimal, you can add all the headers you need anyway)

HTTP/1.1 200 OK\r\n
Content-Type: image/gif\r\n
Content-Length: [length in bytes of the image]\r\n
\r\n
[binary data of your image]

显然,您还必须根据图像的类型设置内容类型.

Obviously you also have to set the content type accordingly to the type of your image.

您可以使用sprintf构建标题,然后使用memcpy在最后一个\r\n

You can build the headers with a sprintf, then memcpy the binary data of the image just after the last \r\n

确保toreturn缓冲区足够大.

这篇关于如何在C中通过HTTP协议发送图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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