Send binary file in HTTP response using C sockets

前端 未结 4 1598
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  萌比男神i
    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);
    

提交回复
热议问题