c++ - Linux CGI Web API - 如何在 C++ 下标准输出二进制 JPEG 图像?

标签 c++ linux cgi jpeg cout

我正在编写一个 Web API,在 linux 下使用 CGI。一切都很好,使用 gcc。我正在向主机返回图像 (jpeg):std::cout << "Content-Type: image/jpeg\n\n"现在必须发送二进制 jpeg 图像。将图像加载到 char* 缓冲区和 std::cout << buffer;不起作用。我确实得到了一张空图像。我怀疑标准输出在第一个 00 字节处停止。

我从网络服务器收到带有不完整图像的 200 OK。

我打算重定向到设备上打开的文件夹中的文件,但这必须是安全传输,并且知道 url 的任何人都无法访问。

我被难住了!

代码片段如下所示:

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;

最佳答案

正如已经向您指出的那样,您需要使用 write() 而不是 IO 格式化操作。

但您甚至不需要这样做。您无需手动将一个文件复制到另一个文件,一次复制一个缓冲区,届时 iostreams 会很乐意为您做这件事。

std::ifstream is;
is.open(imagePath.c_str(), std::ios::in | std::ios::binary);
if (is.is_open())
{
    std::cout << is.rdbuf();
}

差不多就这些了。<​​/p>

关于c++ - Linux CGI Web API - 如何在 C++ 下标准输出二进制 JPEG 图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32386972/

相关文章:

c - 我的 sscanf 格式有什么问题

c++ - 如果我显式定义带参数的构造函数,是否仍会创建默认构造函数?

linux - 如何在循环中附加到 screen session ?

c++ - 如何使用 std::accumulate 对单独定义的索引指向的 vector 中的值进行巧妙的求和(替换循环)

python - 具有 shutil 模块的最低版本的 Python 是什么?

linux - 使用 crontab 启动 wiremock-standalone 时出现问题

python - 确定 Python 脚本是在本地执行还是作为 CGI 执行

perl - 如何在没有 apache 的情况下运行我的 perl CGI 脚本?

c++ - 将字符传递给运算符重载的自定义流操纵器

c++ - 如何在非托管 C++ 中设置区域性信息?