所以,我用 C 语言制作了一个网络服务器,用于显示传感器温度以及使用 gnuplot 制作的 png 格式的绘图。 我在发送 http 模板和 png 图像时遇到问题。我可以发送包含所有数据的 http 模板,但最终无法附加图像。
static const char response_http_template[] = {
"HTTP/1.1 200 OK \
Date: Mon, 27 Jul 2009 12:28:53 GMT \
Server: Apache/2.2.14 (Win32) \
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT \
Content-Length: %lu \
Content-Type: text/html \
Connection: Closed \
\n\n \
%s \
%s"
};
static const char response_page_template[] = {
"<!DOCTYPE html> \
<html> \
<head> \
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /> \
<meta charset=\"utf-8\" /> \
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> \
more html code with some %s
}
void send_response_data(uint32_t sock_client,
const char *student_name,
last_temp_t *last_temp)
{
char write_buf[8192] = { 0 };
char out_buf[8192] = { 0 };
struct stat filestat;
char filesize[7];
int fd;
char file_buf[1024] = {0};
char result;
FILE *fp;
if ( ((fd = open ("./sup/data.png", O_RDONLY)) < -1) || (fstat(fd, &filestat) < 0) ) {
printf ("Error in measuring the size of the file");
}
sprintf (filesize, "%zd", filestat.st_size);
printf("File size %s\n", filesize);
fp = fopen ("./sup/data.png", "r");
if (fp == NULL)
{
perror("fopen error");
exit(EXIT_FAILURE);
}
fread(file_buf, sizeof(char), filestat.st_size + 1, fp);
fclose(fp);
sprintf(
write_buf, response_page_template, student_name, last_temp->timestamp, last_temp->temp);
sprintf(out_buf, response_http_template, strlen(write_buf) + strlen(file_buf), write_buf, file_buf);
write(sock_client, out_buf, strlen(out_buf));
}
当我用 chrome 启动客户端时,我看到 http 代码是正确的,但图像没有显示,只有这样的文本:�PNG
关于如何发送二进制数据有什么想法吗?或者如果我需要更改 http 模板中的某些内容?
谢谢
最佳答案
这里有两种可能的路径:
- 检查请求网址,并根据网址发送 HTML 页面或图像,或者
- 使用数据网址合并两者
对于选项 #1,“主”服务器必须检查 URL 是否指向/image/(或代表图像的其他文件夹)。
对于选项 #2,数据 URL(谷歌搜索,或查看:https://en.wikipedia.org/wiki/Data_URI_scheme
img src="data:image/png;base64,iVBORw0KGgoAAA
ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4
//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU
5ErkJggg==" alt="Red dot" />
您将需要 Base64 编码器将文件从二进制转换为文本。
关于c - C中通过http发送图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58859315/