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

 

 

1.PHP4.23在WindowsXP下的IIS和Apache2两种服务器上的安装实例 http://www.phpe.net/articles/260.shtml 2.Apache服务器配置全攻略(一)http://www.phpe.net/articles/94.shtml 3.WinXp sp1+apache2.0+php5.0+mysql+ phpMyAdmin 安装全功略[教学]http://warmsun.51.net/article/show.php?id=207 1.两种Web服务器(IIS和Apache)可同时存在,只要保证他们的监听端口号不同即可,如:IIS用默认的80,而将Apache的配置为8080。 也可暂时让IIS停止服务,而让Apache用80。 2.在D:\apache2\Apache2\conf下的httpd.conf中,注释符号为#,但不能在一条未注释语句的后面添加注释内容,否则出错,如: httpd.conf中的第173行LoadModule php5_module modules/php5apache2.dll后就不可,否则提示"LoadModule takes two arguments,a module name and the name of a shared object file to load it from". 编写的php文件必须放在Apache2\htdocs文件夹下。 3.要修改的文件及内容: (1)D:\program files\php-5.0.0RC3-Win32下的php.ini-dist 文件 改名为php.ini 搜索extension_dir = ./ 这行,并将其路径指到你的PHP5目录下的ext目录,比如:    extension_dir = "D:\program files\php-5.0.0RC3-Win32\ext" 第545行改为extension=php_mysql.dll (2)D:\apache2\Apache2\conf下的httpd.conf文件 第173行改为LoadModule php5_module modules/php5apache2.dll 前提是将php5apache2.dll(在D:\program files\php-5.0.0RC3-Win32下)复制到D:\apache2\Apache2\modules下。 第761行#AddType application/x-tar .tgz下添加如下内容: AddType application/x-httpd-php .php AddType image/x-icon .ico 找到: #NameVirtualHost * 修改为: NameVirtualHost 127.0.0.1 //或localhost 找到: <VirtualHost 127.0.0.1> 修改下面几行: ServerAdmin (你刚才安装时候输入的管理员信箱) DocumentRoot D:\apache2\Apache2\htdocs ServerName Apache2 # ErrorLog logs/dummy-host.example.com-error_log # CustomLog logs/dummy-host.example.com-access_log common </VirtualHost> 增加默认文件: 找到DirectoryIndex 这行,可以这样修改,添加默认的文件名: DirectoryIndex index.php default.php index.htm index.html default.htm default.html 最后,在该文件末尾加上下面两行 ScriptAlias /php/ "D:\program files\php-5.0.0RC3-Win32" Action application/x-httpd-php "/php/php.exe" 119行修改为Listen 8080,即端口号为8080,80已被IIS占用了。 213行修改为ServerName 127.0.0.1:8080 240行修改为<Directory "D:\program files\php-5.0.0RC3-Win32"> 255行修改为<Directory "D:/apache2/Apache2/htdocs"> 632行左右将# DefaultLanguage nl修改为DefaultLanguage GB2312,即默认语言是简体中文。 709行左右将AddDefaultCharset ISO-8859-1修改为AddDefaultCharset gb2312,即增加默认的字符集为简体中文。 若不修改上面两行,则显示的文字是乱码?修改后并不会立刻改过来,好象重启系统或计算机后才好。 (3)要复制的文件: PHP5的"php5ts.dll"复制到C:\WINDOWS\system32目录下. PHP5的PHP.ini(按上面所述修改)和LibMysql.dll必须都放在windows目录下,才支持mysql。 到此Apache的PHP环境已经完全建立了 测试:   用记事本新建个文件,写下下面几行,保存到D:\apache2\Apache2\htdocs目录下, 这个目录就是你的站点跟目录,命名为phpinfo.php.然后在浏览器中输入http://localhost/phpinfo.php就可以看到想尽的关于PHP的信息了。 <? phpinfo(); ?> 4. 如果万一不知道自己改的哪一个部分使Apache启动不起来了,你可以切换到Apache安装目录下的Conf文件夹, 将http.conf文件删除掉,再将Apache的默认配置文件httpd.default.conf改名成http.conf即可。如果你想进一步的了解Apache的配置, 可以参考一下本站的另一篇文章"Apache服务器配置全攻略"(http://www.phpe.net/?n=ReadArticle&a=94)。 5.遇到的问题及解决办法: 4.将php5apache2.dll(在D:\program files\php-5.0.0RC3-Win32下)复制到D:\apache2\Apache2\modules下。 若直接写成LoadModule php5_module D:\program files\php-5.0.0RC3-Win32\php5apache2.dll,则也提示LoadModule takes two arguments,a module name and the name of a shared object file to load it from". 若直接写成LoadModule php5_module modules/php5apache2.dll,而事先未将php5apache2.dll(在D:\program files\php-5.0.0RC3-Win32下) 复制到D:\apache2\Apache2\modules下,则在点击 开始|所有程序|Apache HTTP Server 2.0.50|Configure Apache Server|Test Configuration 时提示"Cannot load D:/apache2/Apache2/modules/php5apache2.dll into server: \xd5\...",到D:/apache2/Apache2/modules/一看,发现 没有php5apache2.dll这样的文件,所以将其复制过去即可。 5.之后测试配置(Test Configuration)成功(成功后的显示是闪一下就消失了),但启动(Start)时,提示一个警告“PHP Startup: Unable to load dynamic library 'd:\program files\ php-5.0.0RC3-Win32\ext\msql.dll' -找不到指定的模块。”,但连续提示两次后Apache Server启动了,为了连警告都没有,我试着 将msql.dll(在D:\program files\php-5.0.0RC3-Win32下)复制到D:\program files\php-5.0.0RC3-Win32\ext下,但此时重新启动是提示警告 “PHP Startup: Invalid library (maybe not a PHP library) 'msql.dll'”。同样地,连续提示两次后Apache Server启动了,此时,运行 几个简单的程序没问题,但不知这个警告有什么后患,拭目以待吧。 原因是php.ini文件中的extension=msql.dll,将他改为extension=php_mysql.dll即可,但要将libmysql.dll复制到C:\WINDOWS下才可。 6.结果发现将libmysql.dll(在D:\program files\php-5.0.0RC3-Win32下)复制到C:\WINDOWS下,这个问题就迎人而解了。此时,再次启动 Apache Server时就没任何问题了,但有时会出现异常情况:发送错误报告之类的,但这种情况很少。 7.第一次装的是mysql5.0alpha,但显示的数据库只有test,而没有mysql,但显示mysql的表时却能全部显示,后来将mysql5.0alpha 删除改装mysql4.0,尽管在my.ini中修改了datadir和basedir(修改为mysql4.0的),但在WinMySQLAdmin1.4中的Variables选项卡中显示的内容仍是有关mysql5.0alpha 的内容,如:datadir和basedir。以上工作是在一小时内完成的,结果到第二天,WinMySQLAdmin1.4才开始重新启动,但速度很慢 (本身启动速度就很慢,好象得3-4个小时吧)。右键“红绿灯”图标,选择Win NT下的Install the Service,最后再Start the Service。 这时,绿灯亮,表示启动了。发现Variables选项卡中显示的内容正确了。但在Databases选项卡中显示的还只是test数据库,没有mysql. 在WinMySQLAdmin1.4没有启动前,点击mysql\bin下的mysql.exe时,只显示黑屏,或很快闪过出现 "ERROR 2003: Can''t connect to MySQL server on ''localhost'' (10061)“,。 而启动后,显示mysql>提示符。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值