为什么我会得到奇怪的输出而不是图像

时间:2017-04-23 20:59:52

标签: c image

  

当将文件数据读入file_buff然后使用send()将数据发送到浏览器时,我得到奇怪的数据,如this->(ÿØÿà JFIF ),而不是应该显示的图像。我可以将文本等数据发送到浏览器,但似乎无法发送图像数据。

void *connectionThread(void *socket_desc){

    char buffer[100000];
    int newsockfd = *(int*)socket_desc;
    int n;
    magic_t myt = magic_open(MAGIC_ERROR|MAGIC_MIME_TYPE);
    magic_load(myt,NULL);
    char file_buff [800000];
    struct stat filestat;
    bzero(buffer,256);
    FILE * fp;

 while (1)
     {memset(buffer, 0, 100000);n = read(newsockfd,buffer,100000);
     if (n < 0) error("ERROR reading from socket");
     printf("it is something here: %s",buffer);

    char *token = strtok(buffer," ");
    if(token !=NULL)
        token = strtok(NULL, " ");
    token = strtok(token,"\n");
    token = strtok(token,"/");

    fp = fopen ("Koala.jpg", "rb");

    write(newsockfd,"Content-Length: 780831\r\n",strlen("Content-Length: 780831\n"));

    write(newsockfd,"Content-Type: ",strlen("Content-type: "));
    write(newsockfd,magic_file(myt,token),strlen(magic_file(myt,token))); //get Content-type
    write(newsockfd,"\n\n",strlen("\n\n"));
            //knowing the size of image is 780831
    fread(file_buff, sizeof(char), 780831 + 1, fp);
        fclose(fp);
        send(newsockfd, file_buff, 780831,0);



    if ((strncmp(buffer,"quit",4) == 0)) //quit
    break;
    n = write(newsockfd,"I got your message\n May I have another\n",40);
        if (n < 0) error("ERROR writing to socket");

        write(newsockfd,"Ok, I am quitting\n",18);
     }  

    close(newsockfd);
    magic_close(myt);
    pthread_exit(NULL);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您必须更改要发送的标头。将内容类型设置为多部分数据。 HTTP / 1.1 200 OK \ r \ ncontent-type:multipart \ r \ nncontent-length:%ld \ r \ n \ nConnnection:Close; 我认为这应该可以解决你的问题。