1. 程式人生 > >MFC 上傳檔案函式 (利用 CHttpFile 上傳 )

MFC 上傳檔案函式 (利用 CHttpFile 上傳 )

上傳本地檔案至伺服器指定位置

//上傳本地檔案至伺服器指定位置
BOOL UploadFile(LPCTSTR strURL, //負責接收上傳操作的頁面的URL
           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; //解析網路url 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);//將檔案資料讀取到buff const int nTimeOut = 5000;//5秒超時 cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut); //聯接超時設定 cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1); //重試1次 pHC = cis.GetHttpConnection(strServer, wPort); //取得一個Http聯接 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] = ""; //pEx->GetErrorMessage(sz, 25); 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; }