Send binary file in HTTP response using C sockets

前端 未结 4 1540
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 06:44

I`m trying to send a binary file (png image) in http response.

FILE *file;
char *buffer;
int fileLen;

//Open file
file = fopen(\"1.png\", \"rb\");
if (!file         


        
相关标签:
4条回答
  • 2020-12-10 06:59

    The problem is that your message body is being treated as a null-terminated text string (you use strcat and strlen on it), when it isn't one: it is binary data (a PNG file). Therefore, strcat and strlen both stop on the first 0 byte in the image (typically quite early).

    Your program is even printing out the response body: notice that it gives the correct header, but that once the PNG header (binary data) starts, there is only a few bytes.

    1. The line strcat(reply, buffer), where buffer potentially contains 0 bytes. Change it to memcpy(reply+strlen(header), buffer, fileLen).
    2. The line send(client, reply, strlen(reply), 0), where reply potentially contains 0 bytes. Pre-calculate the length of the reply, or replace the strlen with strlen(header)+fileLen.

    Another bug is that you aren't closing the connection when you're done, so the browser will just wait forever. You need this, after send:

    close(client);
    
    0 讨论(0)
  • 2020-12-10 07:08

    The HTTP protocol specifies that it expects "\r\n" instead of "\n". Try that. :)

    0 讨论(0)
  • 2020-12-10 07:12
    strcat(reply, buffer); // this is incorrect, because png(buffer) may contain zero byte
    send(client, reply, strlen(reply), 0);
    strlen(reply) // this is incorrect, because png may contain zero byte
    
    0 讨论(0)
  • 2020-12-10 07:14

    I tried to follow what you did but could not get it to work. Instead, I found it easier to just send header and file separately.

    e.g.

    send(client, header, strlen(header), 0);
    send(client, buffer, fileLen + 1, 0);
    
    0 讨论(0)
提交回复
热议问题