我用来URLDownloadToFile()将图像从网络服务器下载到桌面上的目录中。如果我不想将图像保存到磁盘,而是想将它们读入内存(例如字节数组或 base64 字符串等),是否有类似的函数URLDownloadToFile()可以实现此目的?
有URLOpenStream(),URLOpenBlockingStream()和URLOpenPullStream()允许您下载到内存中。
在这三个中,URLOpenBlockingStream()似乎是最直接使用的,因为它返回一个IStream指针,您可以在循环中同步读取该指针。尽管它不是一个万能的功能,但URLDownloadToFile()使用起来并不困难。
这是一个完整的示例控制台应用程序URLOpenBlockingStream()。它从 URL 下载并将响应写入标准输出。相反,您可以将响应存储在 a 中std::vector或对其执行任何您喜欢的操作。
#include <Windows.h>
#include <Urlmon.h> // URLOpenBlockingStreamW()
#include <atlbase.h> // CComPtr
#include <iostream>
#pragma comment( lib, "Urlmon.lib" )
struct ComInit
{
HRESULT hr;
ComInit() : hr( ::CoInitialize( nullptr ) ) {}
~ComInit() { if( SUCCEEDED( hr ) ) ::CoUninitialize(); }
};
int main(int argc, char* argv[])
{
ComInit init;
// use CComPtr so you don't have to manually call Release()
CComPtr<IStream> pStream;
// Open the HTTP request.
HRESULT hr = URLOpenBlockingStreamW( nullptr, L"http://httpbin.org/headers", &pStream, 0, nullptr );
if( FAILED( hr ) )
{
std::cout << "ERROR: Could not connect. HRESULT: 0x" << std::hex << hr << std::dec << "\n";
return 1;
}
// Download the response and write it to stdout.
char buffer[ 4096 ];
do
{
DWORD bytesRead = 0;
hr = pStream->Read( buffer, sizeof(buffer), &bytesRead );
if( bytesRead > 0 )
{
std::cout.write( buffer, bytesRead );
}
}
while( SUCCEEDED( hr ) && hr != S_FALSE );
if( FAILED( hr ) )
{
std::cout << "ERROR: Download failed. HRESULT: 0x" << std::hex << hr << std::dec << "\n";
return 2;
}
std::cout << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7278 次 |
| 最近记录: |