在C中使用HTTP POST上传JPEG

时间:2014-01-21 14:39:29

标签: c linux http-post jpeg

我正在尝试使用C语言中的HTTP POST编写代码以将JPEG图像发送到服务器。 在我的代码中,我正在尝试构建http post请求(标题,边界,内容等...)。在这种情况下,内容是JPEG图像。服务器端的映像已损坏。我想知道我的代码中可能出现什么问题..

对于那些可能建议使用curl的人:我知道curl可能会为我节省很多工作,但我在linux框中运行此代码,遗憾的是它不支持curl ..


更新:我稍微编辑了我的代码(代码已在下面更新),并比较了客户端和服务器端的两个文件,在服务器端我发现所有00都丢失了...有趣的事实但我仍然无法弄清楚为什么会这样做

#define MAXLINE 38400
#define FILESIZE 37632
#define MAXSUB  38016

char boundary[40] = "---------------------------";

ssize_t process_http(int sockfd, char *host, char *page, char *boundary, char *poststr)
{
    char sendline[MAXLINE + 1], recvline[MAXLINE + 1];
    ssize_t n;
    snprintf(sendline, MAXLINE,
     "POST /%s HTTP/1.0\r\n"
     "Host: %s\r\n"
     "Content-type: multipart/form-data; boundary=%s\r\n"
     "Content-length: %d\r\n\r\n"
     "%s", page, host, boundary, strlen(poststr), poststr);
    write(sockfd, sendline, strlen(sendline));
    while ((n = read(sockfd, recvline, MAXLINE)) > 0) {
    recvline[n] = '\0';
    printf("%s", recvline);
    }
    return n;
}

在MAIN:

//...
//socket initialization
//...


if ((fp = fopen(filename, "rb")) == NULL){
   printf("File could not be opened\n");
   exit(1);
}
else{
   while((ch = getc(fp)) != EOF){
        sprintf( &fileline[strlen(fileline)], "%c", ch );
    }
    fclose(fp);
}

snprintf(poststr, MAXSUB,
     "--%s\r\nContent-Disposition: form-data;"
     "name=\"file\"; filename=\"%s\"\r\nContent-Type: text/plain\r\n\r\n"
     "%s\r\n\r\n"
     "--%s\r\n"
     "Content-Disposition: form-data; name=\"boxkey\"\r\n\r\n%s\r\n"
     "--%s--", boundary, filename, fileline, boundary, key, boundary);

//...
//then make socket connection...
//...

process_http(sockfd, hname, page, boundary, poststr);

//then close socket and return...

1 个答案:

答案 0 :(得分:1)

它已损坏,因为您尝试使用字符串函数将其添加到您发送的数据包中。您必须记住,C字符串函数使用字符'\0'(ASCII字母表中为零)用作字符串终止符。 snprintf函数第一次在图像数据中找到零字节时,它认为“字符串”在那里结束。

也可能是您读取的二进制文件,您首先在 text -mode中打开,这意味着可能会有换行符转换。您还可以使用换行符替换零,这对于二进制数据也是错误的。