windows基于阿帕奇+PHP服务器,实现vc++文件上传功能

如何安装和配置阿帕奇服务器

请参考:http://blog.csdn.net/wujunokay/article/details/12707259

如何安装和配置PHP服务器

请参考:http://blog.csdn.net/wujunokay/article/details/12833127

PHP服务端程序

在upload_file.php里写代码如下:

<?php

//$file = $_GET['filename'];
//file_put_contents("aaa.txt", var_export($file,true));
file_put_contents("abb.txt", var_export($_FILES,true));

 upload_file();


function upload_file()
{
$error;
if ($_FILES["trackdata"]["error"] > 0)
  {
    //echo "Error: " . $_FILES["trackdata"]["error"] . "<br />";
    $error = "200";
  }
  else
  {
    //echo "Upload: " . $_FILES["trackdata"]["name"] . "<br />";
    //echo "Type: " . $_FILES["trackdata"]["type"] . "<br />";
    //echo "Size: " . ($_FILES["trackdata"]["size"] / 1024) . " Kb<br />";
    //echo "Stored in: " . $_FILES["trackdata"]["tmp_name"]. "<br />" ;
  }
  
  if (file_exists("upload/" . $_FILES["trackdata"]["name"]))
  {
      //echo $_FILES["trackdata"]["name"] . " already exists. ";
      
      $error = "201";
  }
  else
  {
      move_uploaded_file($_FILES["trackdata"]["tmp_name"],"upload/" . $_FILES["trackdata"]["name"]);
      //echo "Stored in: " . "upload/" . $_FILES["trackdata"]["name"];
      
      $error = 202; 
   }
   
   echo $error ;
   return $error;

}
     
?>


这个代码比较基本,也就是一个demo,不过还是要感谢北京做php的那个哥们的热心帮助。

 

c++客户端程序

先上代码:

1.请求消息头函数:

 

CString CDlgUpFile::MakeRequestHeaders1(CString& strBoundary)
{
	CString strFormat;
	CString strData;
	strFormat = _T("Content-Type: multipart/form-data; boundary=%s\r\n");
	strData.Format(strFormat, strBoundary);

	return strData;
}

 

2.数据头函数:

CString CDlgUpFile::MakePreFileData1(CString& strBoundary, CString& strFileName, int iRecordID)
{
	CString strFormat;
	CString strData;
	strFormat += _T("--%s");
	strFormat += _T("\r\n");
	strFormat += _T("Content-Disposition: form-data; name=\"recordid\"");
	strFormat += _T("\r\n\r\n");
	strFormat += _T("%d");
	strFormat += _T("\r\n");
	strFormat += _T("--%s");
	strFormat += _T("\r\n");
	strFormat += _T("Content-Disposition: form-data; name=\"trackdata\"; filename=\"%s\"");
	strFormat += _T("\r\n");
	//strFormat += _T("Content-Type: audio/wav");
	strFormat += _T("Content-Type: application/x-www-form-urlencoded");
	strFormat += _T("\r\n");
	strFormat += _T("Content-Transfer-Encoding: binary");
	strFormat += _T("\r\n\r\n");
	strData.Format(strFormat, strBoundary, iRecordID, strBoundary, strFileName);

	return strData;
}


3.数据结束函数:

CString CDlgUpFile::MakePostFileData1(CString& strBoundary)
{
	CString strFormat;
	CString strData;
	strFormat = _T("\r\n");
	strFormat += _T("--%s");
	strFormat += _T("\r\n");
	strFormat += _T("Content-Disposition: form-data; name=\"submitted\"");
	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;
}


4.上传函数:

//上传文件数据至HTTP服务器
int CDlgUpFile::UploadFile1(const CString &szServerURL, const CString &szUploadFileName,CString &szRecvData)
{
	if (szServerURL.IsEmpty() || szUploadFileName.IsEmpty())
	{
		return -1;
	}
	BOOL bRet = FALSE;
	DWORD dwServiceType = 0; 
	CString strServer = _T("");
	CString strObject = _T("");
	INTERNET_PORT nPort = 0;
	bRet =  AfxParseURL(szServerURL, dwServiceType, strServer, strObject, nPort);
	if(!bRet)
	{
		return -2;
	}

	int nRet = 0;
	CInternetSession Session;
	CHttpConnection * pHttpConnection = NULL;
	CFile fTrack;
	CHttpFile* pHTTPFile = NULL;
	CString strHTTPBoundary = _T("");
	CString strPreFileData = _T("");
	CString strPostFileData = _T("");
	DWORD dwTotalRequestLength;
	DWORD dwChunkLength = 0;
	DWORD dwReadLength = 0;
	DWORD dwResponseLength = 0;
	TCHAR szError[MAX_PATH] = {0};
	void* pBuffer = NULL;
	LPSTR szResponse = NULL;
	CString strResponse = _T("");
	BOOL bSuccess = TRUE;
	CString strDebugMessage = _T("");

	if (FALSE == fTrack.Open(szUploadFileName, CFile::modeRead | CFile::shareDenyWrite))
	{
		//AfxMessageBox(_T("Unable to open the file."));
		return -3;
	}

	int nPos = szUploadFileName.ReverseFind('\\');
	CString strFileName = szUploadFileName.Mid(nPos+1);//不带路径的文件名

	int iRecordID = 1;
	strHTTPBoundary = _T("----istroop----");
	strPreFileData = MakePreFileData1(strHTTPBoundary, strFileName, iRecordID);
	strPostFileData = MakePostFileData1(strHTTPBoundary);
	m_dwFileSize = fTrack.GetLength();
	dwTotalRequestLength = strPreFileData.GetLength() + strPostFileData.GetLength() + m_dwFileSize;
	dwChunkLength = 64 * 1024;
	pBuffer = malloc(dwChunkLength);
	if (NULL == pBuffer)
	{
		fTrack.Close();
		return -4;
	}

	try
	{
		pHttpConnection = Session.GetHttpConnection(strServer,nPort);
		pHTTPFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
		pHTTPFile->AddRequestHeaders(MakeRequestHeaders1(strHTTPBoundary));
		pHTTPFile->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);
	#ifdef _UNICODE
		USES_CONVERSION;
		pHTTPFile->Write(W2A(strPreFileData), strPreFileData.GetLength());
	#else
		pHTTPFile->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength());
	#endif
		
		dwReadLength = -1;
		m_dwUploadSize = 0;
		while (0 != dwReadLength)
		{
			//  strDebugMessage.Format(_T("%u / %un"), fTrack.GetPosition(), fTrack.GetLength());
			//  TRACE(strDebugMessage);
			dwReadLength = fTrack.Read(pBuffer, dwChunkLength);
			if (0 != dwReadLength)
			{
				m_dwUploadSize += dwReadLength;
				pHTTPFile->Write(pBuffer, dwReadLength);
			}
		}
	#ifdef _UNICODE
		pHTTPFile->Write(W2A(strPostFileData), strPostFileData.GetLength());
	#else
		pHTTPFile->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength());
	#endif

		pHTTPFile->EndRequest(HSR_SYNC);
		dwResponseLength = pHTTPFile->GetLength();
		while (0 != dwResponseLength)
		{
			szResponse = (LPSTR)malloc(dwResponseLength + 1);
			szResponse[dwResponseLength] = '\0';
			pHTTPFile->Read(szResponse, dwResponseLength);
			strResponse += szResponse;
			free(szResponse);
			szResponse = NULL;
			dwResponseLength = pHTTPFile->GetLength();
		}
		szRecvData = strResponse;
	}
	catch (CException* e)
	{
		//  e->GetErrorMessage(szError, MAX_PATH);
		//  e->Delete();
		nRet = -5;
	}

	if (NULL != pHTTPFile)
	{
		pHTTPFile->Close();
		delete pHTTPFile;
		pHTTPFile = NULL;
	}

	fTrack.Close();
	if (NULL != pBuffer)
	{
		free(pBuffer);
		pBuffer = NULL;
	}

	return nRet;
}


代码分析

1.http协议部分

	CInternetSession Session;
	CHttpConnection * pHttpConnection = NULL;
	CHttpFile* pHTTPFile = NULL;


	pHttpConnection = Session.GetHttpConnection(strServer,nPort);
	pHTTPFile = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
	pHTTPFile->AddRequestHeaders(MakeRequestHeaders1(strHTTPBoundary));
	pHTTPFile->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);


这里用到了CInternetSession、CHttpConnection、CHttpFile。

2.文件操作

用的是CFile fTrack;

3.数据传送

消息头:

  pHTTPFile->AddRequestHeaders(MakeRequestHeaders1(strHTTPBoundary));

请求数据长度:
  pHTTPFile->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);

数据头:

 #ifdef _UNICODE
  USES_CONVERSION;
  pHTTPFile->Write(W2A(strPreFileData), strPreFileData.GetLength());
 #else
  pHTTPFile->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength());
 #endif

文件数据,循环读取文件和发送:

   dwReadLength = fTrack.Read(pBuffer, dwChunkLength);
   if (0 != dwReadLength)
   {
    m_dwUploadSize += dwReadLength;
    pHTTPFile->Write(pBuffer, dwReadLength);
   }

文件结束:

 #ifdef _UNICODE
  pHTTPFile->Write(W2A(strPostFileData), strPostFileData.GetLength());
 #else
  pHTTPFile->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength());
 #endif

 

 

转载请注明原创链接:http://blog.csdn.net/wujunokay/article/details/12834649

 

 

你可能感兴趣的:(C++,文件上传,HTTP服务器,vc++)