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
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.
strcat(reply, buffer)
, where buffer
potentially contains 0 bytes. Change it to memcpy(reply+strlen(header), buffer, fileLen)
.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);
The HTTP protocol specifies that it expects "\r\n" instead of "\n". Try that. :)
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
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);