我试图通过套接字将所有类型的文件发送到C++中的浏览器。我能够发送。 txt
和.html
文件通过套接字很好,但是当我尝试发送JPEG时,出现错误The image "localhost:8199/img.jpg" cannot be displayed because it contains errors
。我不知道为什么我的程序可以正常发送文本文件,但无法处理图像。这是我读文件,并将其写入到客户端:当在C++中通过套接字发送图像时,“图像无法显示错误”
int fileLength = read(in, buf, BUFSIZE);
buf[fileLength] = 0;
char *fileContents = buf;
while (fileLength > 0) {
string msg = "HTTP/1.0 200 OK\r\nContent-Type:" + fileExt + "\r\n\r\n\r\nHere is response data";
int bytes_written;
if(vrsn == "1.1" || vrsn == "1.0"){
write(fd, msg.c_str(), strlen(msg.c_str()));
bytes_written = write(fd, fileContents, fileLength);
} else {
bytes_written = write(fd, fileContents, fileLength);
}
fileLength -= bytes_written;
fileContents += bytes_written;
}
全部代码是在这里:http://pastebin.com/vU9N0gRi
如果我查一下我的浏览器的网络控制台响应报头,我看到Content-Type
是image/jpeg
所以我不确定我做错了什么。
图像文件的处理方式与普通文本文件不同吗?如果是这样,为了处理将图像文件发送到浏览器,我必须做些什么?
损坏头和坏的长度(图片不是字符串)。 –