这个只是一个简单的测试程序
#include "afxinet.h"
#include <string>
using namespace std;
BOOL UploadFile(LPCTSTR strURL, //负责接收上传操作的页面的URL
LPCTSTR 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-data
strData.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 server
unsigned 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;
}
#endif
pHttpConnection = Session.GetHttpConnection(defServerName,nPort);
pHTTP = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, defObjectName);
pHTTP->AddRequestHeaders(MakeRequestHeaders(strHTTPBoundary));//发送包头请求
pHTTP->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);
#if 0
DWORD 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 _UNICODE
pHTTP->Write(strPreFileData, strPreFileData.GetLength());
#else
pHTTP->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength());//写入服务器所需信息
#endif
dwReadLength = -1;
while (0 != dwReadLength)
{
float fPercent = ((float)fTrack.GetPosition())/((float)iLenFileUpload);
dwReadLength = fTrack.Read(pBuffer, dwChunkLength);
if (0 != dwReadLength)
{
pHTTP->Write(pBuffer, dwReadLength);//写入服务器本地文件,用二进制进行传送
}
}
#ifdef _UNICODE
pHTTP->Write(strPostFileData, strPostFileData.GetLength());
#else
pHTTP->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength());
#endif
pHTTP->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, //负责接收上传操作的页面的URL
LPCTSTR 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;
}