我用Linux的open函数和sendfile函数发送文件给浏览器,html文件可以正常显示,但是图片文件发送过去却不能显示。
下面是我使用函数的代码
int Server::openFile(const char* filename)
{
filename = parser.questionMark(filename);
int fd = open(filename, O_RDONLY);
assert(fd >= 0);
fstat(fd, &st);
return fd;
}
void Server::sendResponse(const int& cfd, const int& fd, const int& status, const char* descr, const char* type)
{
char buf[4096]{ '0' };
sprintf(buf, "http/1.1 %d %s\r\n", status, descr);
sprintf(buf + strlen(buf), "content-type: %s\r\n", type);
sprintf(buf + strlen(buf), "content-length: %d\r\n", st.st_size);
send(cfd, buf, strlen(buf), 0);
std::cout << "num:" << sendfile(cfd, fd, NULL, st.st_size);
std::cout << "sendResponse" << std::endl;
}
这是浏览器的请求和我的服务器发送的响应
浏览器显示效果如下所示