【发布时间】:2015-09-03 23:30:56
【问题描述】:
我正在编写一个 Web API,在 linux 下使用 CGI。一切都很好,使用 gcc。我正在向主机返回图像(jpeg):std::cout
我从网络服务器收到 200 OK,但图像不完整。
我打算重定向到设备上打开文件夹中的文件,但这必须是安全的传输,并且不提供给知道该 URL 的任何人。
我被难住了!
sn-p 代码如下:
std:string imagePath;
syslog(LOG_DEBUG, "Processing GetImage, Image: '%s'", imagePath.c_str());
std::cout << "Content-Type: image/jpeg\n\n";
int length;
char * buffer;
ifstream is;
is.open(imagePath.c_str(), ios::in | ios::binary);
if (is.is_open())
{
// get length of file:
is.seekg(0, ios::end);
length = (int)is.tellg();
is.seekg(0, ios::beg);
// allocate memory:
buffer = new char[length]; // gobble up all the precious memory, I'll optimize it into a smaller buffer later
// OH and VECTOR Victor!
syslog(LOG_DEBUG, "Reading a file: %s, of length %d", imagePath.c_str(), length);
// read data as a block:
is.read(buffer, length);
if (is)
{
syslog(LOG_DEBUG, "All data read successfully");
}
else
{
syslog(LOG_DEBUG, "Error reading jpg image");
return false;
}
is.close();
// Issue is this next line commented out - it doesn't output the full buffer
// std::cout << buffer;
// Potential solution by Captain Obvlious - I'll test in the morning
std::cout.write(buffer, length);
}
else
{
syslog(LOG_DEBUG, "Error opening file: %s", imagePath.c_str());
return false;
}
return true;
【问题讨论】:
-
您是否尝试过使用
std::cout.write? -
哦,FWIW 停止使用
buffer = new char[length];之类的东西并使用vector,您的代码会感谢您。 -
感谢男士们的快速回复。我相信你用 std::cout.write 搞定了。多亏了你们,我离明天早上 8:30 的交付成果还有一条线。我应该知道,但我是旧时 printf 用户并强迫自己使用更合适的流。我实际上是一个为 linux 做这个跨平台的 Windows 程序员。关于 Vector/Victor - 我一定会清理并重新发布更新。