首先引入 #include "afxinet.h"
其次准备好HTTP POST服务器
STDMETHODIMP CPostPDFToA4::t5PostPDFToA4(BSTR strFileName, BSTR strFileFullPath, BSTR* pstrMsg)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
// TODO: 在此添加实现代码
USES_CONVERSION;
// TODO: 在此添加实现代码
CString strURL; //负责接收上传操作的页面的URL
CString strLocalFileName;
CString strName;
DWORD dwFileNameLength;
CString strPreFileData;
CString strPostFileData;
CString strHTTPBoundary;
DWORD dwResponseLength;
int iRecordID = 1;
strHTTPBoundary = _T("---------------------------7b4a6d158c9");//定义边界值
// 获取POST地址
ReadXML();
DWORD dwReadLength;
strName = strFileName;//_T("Visual.C++技术内幕_第四版.pdf");
strLocalFileName = strFileFullPath;//_T("C:\\Visual.C++技术内幕_第四版.pdf");
strURL = m_strUrl;// _T("hte");//+ strLocalFileName;
dwFileNameLength = sizeof(strName);
//ASSERT(strURL != NULL && strLocalFileName != NULL);
// 生成传送头数据
strPreFileData = MakePreFileData(strHTTPBoundary, strName, iRecordID);
// 生成传送数据
strPostFileData = MakePostFileData(strHTTPBoundary);
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;
LPSTR szResponse;
//bResult =
// 解析POST地址
AfxParseURL(strURL, dwType, strServer, strObject, wPort);
//if(!bResult)
// return ;
CFile file;
DWORD dwDataSize;
try
{
if(!file.Open(strLocalFileName, CFile::shareDenyNone | CFile::modeRead))
return S_FALSE;
dwFileLength = file.GetLength();
if(dwFileLength <= 0)
return S_FALSE;
//======================================================
file.SeekToBegin();
CByteArray array;
array.SetSize(dwDataSize);
VERIFY( dwDataSize == file.Read(array.GetData(), dwDataSize) );
//file.Close();
//==============================================================
pFileBuff = new char[dwFileLength];
memset(pFileBuff, 0, sizeof(char) * dwFileLength);
const int nTimeOut = 10000;
cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut); //联接超时设置
cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1); //重试1次
pHC = cis.GetHttpConnection(strServer, wPort);//,_T("admin"),_T("admin")); //取得一个Http联接
// 打开连接
pHF = pHC->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
/*pHF->AddRequestHeaders(strName,
HTTP_ADDREQ_FLAG_ADD_IF_NEW,dwFileNameLength );*/
DWORD dwTotalRequestLength;
pHF->AddRequestHeaders(MakeRequestHeaders(strHTTPBoundary));//发送包头请求
dwTotalRequestLength = strPreFileData.GetLength() + strPostFileData.GetLength() + dwFileLength;//计算整个包的总长度
// 发送文件数据流
pHF->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);
#ifdef _UNICODE
pHF->Write(W2A(strPreFileData), strPreFileData.GetLength());
#else
pHF->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength());//写入服务器所需信息
#endif
dwReadLength = -1;
while (0 != dwReadLength)
{
/*strDebugMessage.Format(_T("%u / %u\n"), fTrack.GetPosition(), fTrack.GetLength());
TRACE(strDebugMessage);*/
dwReadLength = file.Read(pFileBuff, dwFileLength);
if (0 != dwReadLength)
{
pHF->Write(pFileBuff, dwReadLength);//写入服务器本地文件,用二进制进行传送
}
}
#ifdef _UNICODE
pHF->Write(W2A(strPostFileData), strPostFileData.GetLength());
#else
pHF->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength());
#endif
pHF->EndRequest(HSR_SYNC);
LPSTR szResponse;
CString strResponse;
dwResponseLength = pHF->GetLength();
while (0 != dwResponseLength)
{
szResponse = (LPSTR)malloc(dwResponseLength + 1);
szResponse[dwResponseLength] = '\0';
pHF->Read(szResponse, dwResponseLength);
strResponse += szResponse;
free(szResponse);
dwResponseLength = pHF->GetLength();
}
/*if(!pHF->SendRequest(NULL, 0, pFileBuff, dwFileLength))
{
delete[]pFileBuff;
pFileBuff = NULL;
pHF->Close();
pHC->Close();
cis.Close();
return;
}*/
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("InternetException occur!\r\n%s", sz);
AfxMessageBox(str);
}
catch(CFileException& fe)
{
CString str;
str.Format("FileException occur!\r\n%d", fe.m_lOsError);
AfxMessageBox(str);
}
catch(...)
{
DWORD dwError = GetLastError();
CString str;
str.Format("Unknow Exception occur!\r\n%d", dwError);
AfxMessageBox(str);
}
delete[]pFileBuff;
pFileBuff = NULL;
file.Close();
pHF->Close();
pHC->Close();
cis.Close();
return S_OK;
}
CString CPostPDFToA4::MakeRequestHeaders(CString &strBoundary)//包头
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
CString strFormat;
CString strData;
strFormat = _T("Content-Type: multipart/form-data; boundary=%s\r\n");//二进制文件传送Content-Type类型为: multipart/form-data
strData.Format(strFormat, strBoundary);
return strData;
}
CString CPostPDFToA4::MakePreFileData(CString &strBoundary, CString &strFileName, int iRecordID)
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
/**/
//Content-Type:
//JPG image/pjpeg
//PNG image/x-png
//BMP image/bmp
//TIF image/tiff
//GIF image/gif
CString strFormat;
CString strData;
//strFormat += _T("--%s");
//strFormat += _T("\r\n");
//strFormat += _T("Content-Disposition: form-data; name=\"test1\"");//除了文件数据,还可以传送其它信息
//strFormat += _T("\r\n\r\n");
//strFormat += _T("my name is xiaoxiong");
//strFormat += _T("\r\n");
//strFormat += _T("--%s");
//strFormat += _T("\r\n");
//strFormat += _T("Content-Disposition: form-data; name=\"test2\"");
//strFormat += _T("\r\n\r\n");
//strFormat += _T("哈哈");
//strFormat += _T("\r\n");
strFormat += _T("--%s");
strFormat += _T("\r\n");
strFormat += _T("Content-Disposition: form-data; name=\"upfile\"; filename=\"%s\"");
strFormat += _T("\r\n");
strFormat += _T("Content-Type: text/pdf;charset=utf-8");
strFormat += _T("\r\n\r\n");
strData.Format(strFormat, strBoundary, strFileName);//
return strData;
}
CString CPostPDFToA4::MakePostFileData(CString &strBoundary)//发送请求包
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
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("hello");
strFormat += _T("\r\n");
strFormat += _T("--%s--");
strFormat += _T("\r\n");
strData.Format(strFormat, strBoundary, strBoundary);
return strData;
}
BOOL CPostPDFToA4::ReadXML()
{
AFX_MANAGE_STATE(AfxGetStaticModuleState());
TCHAR buffer[MAX_PATH] = {0};
::GetModuleFileName(NULL, buffer, MAX_PATH);
CString strPath = buffer;
int nIndex = strPath.ReverseFind(_T('\\'));
strPath = strPath.Left(nIndex + 1);
CString strConfigFile = strPath + _T("SendServer.xml");
try{
MSXML2::IXMLDOMDocumentPtr xdoc;
xdoc.CreateInstance(__uuidof(MSXML2::DOMDocument));
if(xdoc == NULL)
{
AfxMessageBox(_T("创建XML文档对象失败"));
return FALSE;
}
xdoc->load(_variant_t(strConfigFile));
MSXML2::IXMLDOMNodeListPtr nodelist = NULL;
nodelist = xdoc->selectNodes(_T("HTTPPOST/服务"));
MSXML2::IXMLDOMNodePtr subnode;
long nodecount;
nodelist->get_length(&nodecount);
for(long i = 0; i < nodecount; i++)
{
subnode = nodelist->nextNode()->selectSingleNode((_bstr_t)_T("URL"));
if(subnode != NULL)
{
_bstr_t str = subnode->Gettext();
if(str.length() > 0)
m_strUrl = (LPCTSTR)str;
}
}
}
catch(...)
{
AfxMessageBox(_T("读取SendServer.xml文件失败"));
return FALSE;
}
return TRUE;
}