上传本地文件至服务器指定位置
BOOL UploadFile(LPCTSTR strURL,
LPCTSTR strLocalFileName)
{
ASSERT(strURL != NULL && strLocalFileName != NULL);
BOOL bResult = FALSE;
DWORD dwType = 0;
CString strServer;
CString strObject;
INTERNET_PORT wPort = 0;
DWORD dwFileLength = 0;
char * pFileBuff = NULL;
CHttpConnection * pHC = NULL;
CHttpFile * pHF = NULL;
CInternetSession cis;
bResult = AfxParseURL(strURL, dwType, strServer, strObject, wPort);
if(!bResult)
return FALSE;
CFile file;
try
{
if(!file.Open(strLocalFileName, CFile::shareDenyNone | CFile::modeRead))
return FALSE;
dwFileLength = file.GetLength();
if(dwFileLength <= 0)
return FALSE;
pFileBuff = new char[dwFileLength];
memset(pFileBuff, 0, sizeof(char) * dwFileLength);
file.Read(pFileBuff, dwFileLength);
const int nTimeOut = 5000;
cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut);
cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);
pHC = cis.GetHttpConnection(strServer, wPort);
pHF = pHC->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
if(!pHF->SendRequest(NULL, 0, pFileBuff, dwFileLength))
{
delete[]pFileBuff;
pFileBuff = NULL;
pHF->Close();
pHC->Close();
cis.Close();
return FALSE;
}
DWORD dwStateCode = 0;
pHF->QueryInfoStatusCode(dwStateCode);
if(dwStateCode == HTTP_STATUS_OK)
bResult = TRUE;
}
catch(CInternetException * pEx)
{
char sz[256] = "";
CString str;
str.Format(_T("InternetException occur!\r\n%s"), sz);
AfxMessageBox(str);
}
catch(CFileException& fe)
{
CString str;
str.Format(_T("FileException occur!\r\n%d"), fe.m_lOsError);
AfxMessageBox(str);
}
catch(...)
{
DWORD dwError = GetLastError();
CString str;
str.Format(_T("Unknow Exception occur!\r\n%d"), dwError);
AfxMessageBox(str);
}
delete[]pFileBuff;
pFileBuff = NULL;
file.Close();
pHF->Close();
pHC->Close();
cis.Close();
return bResult;
}