我正在使用WinInet库进行http(PUT)上传,在WinXP上工作正常,但在Win7上它不起作用,奇怪的是' InterWriteFile' WinInet文件的功能返回true。任何帮助将不胜感激。 在此先感谢。
//this is the first function that is called when upload is requested.
void Upload()
{
//check if handle is already open or not
if(!m_hNetOpen)
{
//open interconnect: Initializes an application's use of the WinINet functions.
m_hNetOpen = InternetOpen("XYZ",
INTERNET_OPEN_TYPE_DIRECT,
NULL,
NULL,
INTERNET_INVALID_PORT_NUMBER);
//return if handle is NULL
if(m_hNetOpen == NULL)
{
return FALSE;
}
}
//we'll get user specified URL, could be some xyz.com too.
if(!m_hNetConnect)
{
//opens HTTP or FTP connection for a site requested...pchServerName requested
m_hNetConnect = InternetConnect(m_hNetOpen,
strServerName,
INTERNET_DEFAULT_HTTP_PORT,
NULL,
NULL,
INTERNET_SERVICE_HTTP,
INTERNET_FLAG_PASSIVE,
dwContext);
//return if handle is NULL
if(m_hNetConnect == NULL)
{
return FALSE;
}
}
dwContext = 0;
//now, create HTTP request
m_hHttpConnect = HttpOpenRequest(m_hNetConnect,
"PUT",
strObjectName,
NULL,
NULL,
NULL,
INTERNET_FLAG_CACHE_IF_NET_FAIL,
dwContext);
//return if handle is NULL
if(m_hHttpConnect == NULL)
{
return FALSE;
}
//call UseHttpSendReqEx
BOOL bRet = UseHttpSendReqEx(m_hHttpConnect, strUploadFileName);
//if not suuceeded log the message
if(!bRet)
{
//Logmessage
}
if(m_hHttpConnect)
{
//close the handle
InternetCloseHandle(m_hHttpConnect);
}
return bRet;
}
//this function is will send HTTP request and writes data to internetfile
BOOL UseHttpSendReqEx(HINTERNET hConnect, char *upFile)
{
INTERNET_BUFFERS BufferIn = {0};
DWORD dwBytesRead = 0;
DWORD dwBytesWritten = 0;
//buffer
BYTE strBuffer[20480] = {0};
BOOL bRead;
BOOL bRet = TRUE;
//get the size of structure
BufferIn.dwStructSize = sizeof(INTERNET_BUFFERS);
//create file
m_hFile = CreateFile(upFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
//check for invalid handle
if (m_hFile == INVALID_HANDLE_VALUE)
{
return FALSE;
}
//get the file size
BufferIn.dwBufferTotal = GetFileSize(m_hFile, NULL);
//send request to HTTP server
if(!HttpSendRequestEx(hConnect, &BufferIn, NULL, HSR_INITIATE, 0))
{
//close the file handle
CloseHandle(m_hFile);
m_hFile = NULL;
return FALSE;
}
DWORD sum = 0;
do
{
//read the file that is to be uploaded
if (!(bRead = ReadFile(m_hFile, strBuffer, sizeof(strBuffer),
&dwBytesRead, NULL)))
{
bRet = FALSE;
break;
}
//write the internet file
bRet=InternetWriteFile(hConnect, strBuffer, dwBytesRead,
&dwBytesWritten);
if(!bRet)
{
DWORD d = GetLastError();
bRet = FALSE;
break;
}
memset(strBuffer, '\0', sizeof(strBuffer));
sum += dwBytesWritten;
}
while(dwBytesRead == sizeof(strBuffer)) ;
//This sleep was introduced as if we immediately after the above loop
//if we try to close the handle then file does not get created on the server
Sleep(100);
BOOL b = CloseHandle(m_hFile);
m_hFile = NULL;
return bRet;
}