我在VC ++中使用win32创建一个应用程序,wininet将图像上传到Flickr。我能够正确地获取Frob,Token但是当我尝试上传图像时,我收到错误帖子大小太大。
标题创建如下
wstring wstrAddHeaders = L"Content-Type: multipart/form-data;boundary=ABCD\r\n";
wstrAddHeaders += L"Host: api.flickr.com\r\n";
wchar_t tempStr[MAX_PATH];
wsprintf(L"Content-Length: %ld\r\n",szTotalSize);
wstrAddHeaders += tmpStr;
wstrAddHeaders +=L"\r\n";
HINTERNET hSession = InternetConnect(hInternet, L"www.flickr.com", INTERNET_DEFAULT_HTTP_PORT, NULL,NULL, INTERNET_SERVICE_HTTP, 0, 0);
if(hSession==NULL)
{
dwErr = GetLastError();
return;
}
Post请求的内容创建如下:
wstring wstrBoundry = L"--ABCD\r\n";
wstring wstrContent =wstrBoundry;
wstrContent +=L"Content-Disposition: form-data; name=\"api_key\"\r\n\r\n";
wstrContent +=wstrAPIKey.c_str() ;
wstrContent += L"\r\n";
wstrContent +=wstrBoundry;
wstrContent +=L"Content-Disposition: form-data; name=\"auth_token\"\r\n\r\n";
wstrContent +=m_wstrToken.c_str();
wstrContent += L"\r\n";
wstrContent +=wstrBoundry;
wstrContent +=L"Content-Disposition: form-data; name=\"api_sig\"\r\n\r\n";
wstrContent +=wstrSig;
wstrContent += L"\r\n";
wstrContent +=wstrBoundry;
wstrContent +=L"Content-Disposition: form-data; name=\"photo\"; filename=\"C:\\test.jpg\"";
wstrContent +=L"\r\n";
wstrContent +=L"Content-Type: image/jpeg\r\n\r\n";
wstring wstrFilePath(L"C:\\test.jpg");
CAtlFile file;
HRESULT hr = S_OK;
hr = file.Create(wstrFilePath.c_str(),GENERIC_READ,FILE_SHARE_READ,OPEN_EXISTING);
if(FAILED(hr))
{
return;
}
ULONGLONG nLen;
hr = file.GetSize(nLen);
if (nLen > (DWORD)-1)
{
return ;
}
char * fileBuf = new char[nLen];
file.Read(fileBuf,nLen);
wstring wstrLastLine(L"\r\n--ABCD--\r\n");
size_t szTotalSize = sizeof(wchar_t) * (wstrContent.length()) +sizeof(wchar_t) * (wstrLastLine.length()) + nLen;
unsigned char *buffer = (unsigned char *)malloc(szTotalSize);
memset(buffer,0,szTotalSize);
memcpy(buffer,wstrContent.c_str(),wstrContent.length() * sizeof(wchar_t));
memcpy(buffer+wstrContent.length() * sizeof(wchar_t),fileBuf,nLen);
memcpy(buffer+wstrContent.length() * sizeof(wchar_t)+nLen,wstrLastLine.c_str(),wstrLastLine.length() * sizeof(wchar_t));
hRequest = HttpOpenRequest(hSession, L"POST", L"/services/upload/", L"HTTP/1.1", NULL, NULL, 0, NULL);
if(hRequest)
{
bRet = HttpAddRequestHeaders(hRequest,wstrAddHeaders.c_str(),wstrAddHeaders.length(),HTTP_ADDREQ_FLAG_ADD | HTTP_ADDREQ_FLAG_REPLACE);
if(bRet)
{
bRet = HttpSendRequest(hRequest,NULL,0,(void *)buffer,szTotalSize);
if(bRet)
{
while(true)
{
char buffer[1024]={0};
DWORD read=0;
BOOL r = InternetReadFile(hRequest,buffer,1024,&read);
if(read !=0)
{
wstring strUploadXML =buffer;
break;
}
}
}
}
我不太确定将图像数据添加到字符串并发布请求的方式。 我需要将图像数据转换为Unicode吗? 任何建议,如果有人能找到我做错了什么对我有用。
答案 0 :(得分:0)
实际上我们不能将Post内容作为unicode发送。 我们可以在Wininet API中使用头文件作为unicode。
一旦我们在char * buffer中读取图像数据,我们就可以将该缓冲区添加到帖子内容字符串中,然后添加最后一行内容。