MFC如何向 http://169.254.1.10:8090/api/v1/~bali/ABC0123456789 发送图片
时间: 2023-10-05 19:07:10 浏览: 182
在MFC中,可以使用WinHTTP库向指定URL发送HTTP请求并上传图片。以下是一个简单的示例代码:
```c++
#include <afxinet.h>
#include <winhttp.h>
BOOL UploadImage(LPCTSTR lpszFilePath, LPCTSTR lpszUrl)
{
// 打开文件
CFile file;
if (!file.Open(lpszFilePath, CFile::modeRead))
{
return FALSE;
}
// 初始化WinHTTP
HINTERNET hSession = WinHttpOpen(L"MFC WinHTTP Example",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS,
WINHTTP_FLAG_ASYNC);
if (!hSession)
{
return FALSE;
}
// 打开连接
HINTERNET hConnect = WinHttpConnect(hSession, L"169.254.1.10", 8090, 0);
if (!hConnect)
{
WinHttpCloseHandle(hSession);
return FALSE;
}
// 打开请求
HINTERNET hRequest = WinHttpOpenRequest(hConnect, L"POST", L"/api/v1/~bali/ABC0123456789",
NULL, WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_REFRESH);
if (!hRequest)
{
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return FALSE;
}
// 设置请求头
CStringA strHeaders = "Content-Type: image/jpeg\r\n";
if (!WinHttpAddRequestHeaders(hRequest, strHeaders, -1L, WINHTTP_ADDREQ_FLAG_REPLACE))
{
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return FALSE;
}
// 发送请求
if (!WinHttpSendRequest(hRequest, NULL, 0, NULL, 0, file.GetLength(), 0))
{
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return FALSE;
}
// 上传数据
DWORD dwBytesWritten = 0;
DWORD dwBytesRead = 0;
BYTE buffer[4096];
while (dwBytesWritten < file.GetLength())
{
DWORD dwBytesToRead = min(sizeof(buffer), file.GetLength() - dwBytesWritten);
file.Read(buffer, dwBytesToRead);
if (!WinHttpWriteData(hRequest, buffer, dwBytesToRead, &dwBytesRead))
{
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return FALSE;
}
dwBytesWritten += dwBytesRead;
}
// 结束请求
if (!WinHttpReceiveResponse(hRequest, NULL))
{
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return FALSE;
}
// 关闭连接
WinHttpCloseHandle(hRequest);
WinHttpCloseHandle(hConnect);
WinHttpCloseHandle(hSession);
return TRUE;
}
```
在调用该函数时,将图片文件路径和目标URL作为参数传入即可:
```c++
UploadImage(L"C:\\Images\\test.jpg", L"http://169.254.1.10:8090/api/v1/~bali/ABC0123456789");
```
阅读全文