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;
}

你可能感兴趣的:(VC/MFC,C++)