本文主要是介绍用MFC 网络接口下载/上传文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
这个只是一个简单的测试程序
#include "afxinet.h"
#include <string>using namespace std;BOOL UploadFile(LPCTSTR strURL, //负责接收上传操作的页面的URLLPCTSTR strLocalFileName); //待上传的本地文件路径BOOL CXXDlg::OnInitDialog()
{....///测试UploadFile(_T(""),_T("E:\\NT800\\vehicle\\DiagSoftware\\Display_Src\\Scan\\Upload\\20161223-090001.txt")) ;//SendFile();return TRUE; // return TRUE unless you set the focus to a control
}
CString MakeRequestHeaders(CString strBoundary)//包头
{CString strData;CString strFormat = _T("Content-Type: multipart/form-data; boundary=%s\r\n");//二进制文件传送Content-Type类型为: multipart/form-datastrData.Format(strFormat, strBoundary);return strData;
}
CString MakePreFileData(CString strBoundary, CString strFileName)
{CString strFormat;CString strData;strFormat += _T("--%s");strFormat += _T("\r\n");strFormat += _T("Content-Disposition: form-data; name=\"Filedata\"; filename=\"%s\"");//文件地址信息strFormat += _T("\r\n");strFormat += _T("Content-Type: application/octet-stream");strFormat += _T("\r\n\r\n");strData.Format(strFormat, strBoundary, strFileName);return strData;
}CString MakePostFileData(CString strBoundary)//发送请求包
{CString strFormat;CString strData;strFormat = _T("\r\n"); strFormat += _T("--%s");strFormat += _T("\r\n");strFormat += _T("Content-Disposition: form-data; name=\"Upload\"");strFormat += _T("\r\n\r\n");strFormat += _T("Submit Query");strFormat += _T("\r\n");strFormat += _T("--%s--");strFormat += _T("\r\n");strData.Format(strFormat, strBoundary, strBoundary);return strData;
}
BOOL GetResult(LPSTR lpStr, int& iRetCode, CString& strRetMsg)
{iRetCode = -1;strRetMsg = _T("");CString strResult /*= lpStr*/, strTmp = _T("");if(strResult.GetLength() == 0)return FALSE;int iStatus = strResult.Find(_T("\"status\":"));if(iStatus == -1)return FALSE;int iMsg = strResult.Find(_T("\"msg\":"));if(iMsg == -1)return FALSE;strTmp = strResult.Mid(iStatus+9,iMsg-iStatus-9);// 1, strTmp.Trim();strTmp.TrimRight(_T(","));iRetCode = _tcstod(strTmp,NULL);int iName = strResult.Find(_T("\"name\":"));if(iName == -1)return FALSE;strTmp = strResult.Mid(iMsg+6,iName-iMsg-6);// "上传文件成功!", strTmp.Trim();strTmp.TrimRight(_T(","));strRetMsg = strTmp;return TRUE;
}
BOOL CTestHTTPDlg::SendFile( )//发送数据
{CString defServerName = _T("www.xxx.com");//服务器名,可以是IP,也可以是网站名称CString defObjectName = _T("/function/upload.ashx?serial=20161223105745_ ");//保存的地址// USES_CONVERSION;CInternetSession Session;CHttpConnection *pHttpConnection = NULL;INTERNET_PORT nPort = 80;///服务器端口这个很重要CFile fTrack;CHttpFile* pHTTP=NULL;CString strHTTPBoundary;CString strPreFileData;CString strPostFileData;DWORD dwTotalRequestLength;DWORD dwChunkLength;DWORD dwReadLength;DWORD dwResponseLength;TCHAR szError[MAX_PATH];void* pBuffer;LPSTR szResponse;BOOL bSuccess = TRUE;if (!fTrack.Open(_T("Upload.zip"), CFile::modeRead | CFile::shareDenyWrite))return FALSE;strHTTPBoundary = _T("-------------------------7b4a6d158c9");//定义边界值strPreFileData = MakePreFileData(strHTTPBoundary, _T("Upload.zip"));strPostFileData = MakePostFileData(strHTTPBoundary);int iLenFileUpload = fTrack.GetLength();dwTotalRequestLength = strPreFileData.GetLength() + strPostFileData.GetLength() + iLenFileUpload;//计算整个包的总长度dwChunkLength = 64 * 1024;pBuffer = malloc(dwChunkLength);if (NULL == pBuffer)return FALSE;try{
#if 0 //test serverunsigned short usPort; //用于保存目标HTTP服务端口CString strServer, strObject; //strServer用于保存服务器地址,strObject用于保存文件对象名称 DWORD dwServiceType=AFX_INET_SERVICE_HTTP; //dwServiceType用于保存服务类型//解析URL,获取信息 if(!AfxParseURL(strPostFileData, dwServiceType, strServer, strObject, usPort)) { //解析失败,该Url不正确 return -1; }
#endifpHttpConnection = Session.GetHttpConnection(defServerName,nPort);pHTTP = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, defObjectName);pHTTP->AddRequestHeaders(MakeRequestHeaders(strHTTPBoundary));//发送包头请求pHTTP->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);#if 0DWORD dwRetCode = 0;pHTTP->QueryInfoStatusCode(dwRetCode);if (dwRetCode != HTTP_STATUS_OK){CString err;err.Format(_T("POST error, error ID: %d"), dwRetCode);TRACE(err);}
#endif#ifdef _UNICODEpHTTP->Write(strPreFileData, strPreFileData.GetLength());
#elsepHTTP->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength());//写入服务器所需信息
#endifdwReadLength = -1;while (0 != dwReadLength){float fPercent = ((float)fTrack.GetPosition())/((float)iLenFileUpload);dwReadLength = fTrack.Read(pBuffer, dwChunkLength);if (0 != dwReadLength){pHTTP->Write(pBuffer, dwReadLength);//写入服务器本地文件,用二进制进行传送}}#ifdef _UNICODEpHTTP->Write(strPostFileData, strPostFileData.GetLength());
#elsepHTTP->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength());
#endifpHTTP->EndRequest(HSR_SYNC);dwResponseLength = pHTTP->GetLength(); while (0 != dwResponseLength) {szResponse = (LPSTR)malloc(dwResponseLength + 1); szResponse[dwResponseLength] = '\0';pHTTP->Read(szResponse, dwResponseLength);DWORD dwRetCode = 0;pHTTP->QueryInfoStatusCode(dwRetCode);int iRetCode = -1;CString strRetMsg = _T("");GetResult(szResponse,iRetCode,strRetMsg);free(szResponse);dwResponseLength = pHTTP->GetLength();if((iRetCode != 1)||(dwRetCode != HTTP_STATUS_OK))bSuccess = FALSE;}} catch (CException* e){e->GetErrorMessage(szError, MAX_PATH);e->Delete();// AfxMessageBox(szError);bSuccess = FALSE;}pHTTP->Close();delete pHTTP;fTrack.Close();if (NULL != pBuffer){free(pBuffer);}return bSuccess;
}BOOL UploadFile(LPCTSTR strURL, //负责接收上传操作的页面的URLLPCTSTR strLocalFileName) //待上传的本地文件路径
{ASSERT(strURL != NULL && strLocalFileName != NULL);BOOL bResult = FALSE;DWORD dwType = 0;CString strServer=_T("www.foxwelltech.com");CString strObject = _T("/function/upload.ashx?serial=20161223105745_ ");INTERNET_PORT wPort = 80;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); //重试1次pHC = cis.GetHttpConnection(strServer, wPort); //取得一个Http联接//pHC = cis.GetHttpConnection(_T("www.baidu.com"), (INTERNET_PORT)(80) ); //取得一个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){LPTSTR sz;CString str = _T("InternetException occur!\r\n");pEx->GetErrorMessage(sz, 25);str += 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;
}
这篇关于用MFC 网络接口下载/上传文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!