您的位置:首页 > 编程语言 > PHP开发

VC实现FTP上传和下载

2014-01-04 17:30 204 查看
一、该代码是实现server-client之间的文件上传下载功能

二、首先涉及到几个自己定义的函数

////////////////////////////////////////////////////////////////////

//该函数实现 client与server建立连接

bool OpenConnection(CString server)

{

 if(server == "")

  return 0;

 

 // put the server name in the CFtpGet class

 strServerName = server;

 

 try {

  // try to connect to a ftp server

  pFtpConnection = pInternetSession->GetFtpConnection(strServerName,

   strUser,

   strPass);

      }

catch (CInternetException* pEx) 

     {

  // if failed, just show the error

  

  // Oops! We failed to connect!

  TCHAR szErr[1024];

  pEx->GetErrorMessage(szErr, 1024);

  TRACE(szErr);

  AfxMessageBox(szErr);

  pEx->Delete();

  return 0;// return 1 but previous error box have been showed

 }

 

 

 return 1;

}

////////////////////////////////////////////////////////////////////////////////////

//该函数实现client与server之间关闭连接

bool CloseConnection()

{

 // close the connection to server, you can reconnect latter

 if(pFtpConnection == NULL)

  return 0;

 try{

  pFtpConnection->Close();

 }catch(...)

 {

  return 0;

 }

 if(pFtpConnection != NULL)

  delete pFtpConnection;

 

 return 1;

}

/////////////////////////////////////////////////////////////////////////////////////

//该函数实现从server下载文件

int GetMultipleFile(CStringArray *remoteArray,

     CStringArray *localArray,

     int number_file)

{

 // init some var

 BOOL goodfile;

 int x=0;

 int nb_lost_file =0;

 

 // while loop to transfer every file in the array

 while(x

 {

  // try to get file

  goodfile = pFtpConnection->GetFile(

   remoteArray->GetAt(x),

   localArray->GetAt(x),

   FALSE,

   FILE_ATTRIBUTE_NORMAL,

   FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE

   );

missed[x] = goodfile ? 0 : 1;

  // if failed, missed[x] become 1

  // if good, missed become 0

  if(missed[x])

   nb_lost_file++;

  // if the file was missed, increase the number of

  // missing file.

  // increase to the next file

  x++;

 }

 //return the number of missing file, if any.

 return nb_lost_file;

}

///////////////////////////////////////////////////////////////////////////////////

//该函数实现从client上传文件

int PutMultipleFile(CStringArray *remoteArray,

     CStringArray *localArray,

     int number_file)

{

 BOOL goodfile;

 int x=0;

 int nb_lost_file =0;

 

 // while loop to transfer every file in the array

 while(x

 {

  // try to get file

goodfile=pFtpConnection->PutFile(

      localArray->GetAt(x),

   remoteArray->GetAt(x),

   FTP_TRANSFER_TYPE_BINARY,

   1

   );

   missed[x] = goodfile ? 0 : 1;

  // if failed, missed[x] become 1

  // if good, missed become 0

  if(missed[x])

   nb_lost_file++;

  // if the file was missed, increase the number of

  // missing file.

  // increase to the next file

  x++;

 }

 //return the number of missing file, if any.

 return nb_lost_file;

 

}

 

////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////

//下面是这些函数的设置及使用

实现上传:

// TODO: Add your control notification handler code here

 strAppName.LoadString(AFX_IDS_APP_TITLE);

 pInternetSession = new CInternetSession(strAppName,INTERNET_OPEN_TYPE_PRECONFIG);

 

 

 if(!pInternetSession)

 {

  AfxMessageBox("Can't start internet session");

 }

 

 

 CString tempRemote;

 CString tempLocal;

 CString folder;

 CString server;

 CStringArray remote;

 CStringArray local;

 CString Error;

 

 

 

 strUser="ABCD";           //用户名

 strPass="EFGH";         //密码

 server="192.168.1.100";    //server的IP

 

 tempRemote="2.txt";        //上传之后显示的文件名

 remote.Add(tempRemote);

 tempLocal = "c:\\download\\1.txt";//上传文件路径及名字

 local.Add(tempLocal);

 

 // open server

 bool conectOK;

 conectOK = OpenConnection(server);

 // transfer multiple file

 if(conectOK)

 {

  PutMultipleFile(&remote,&local,1);

 }

 

 // close connection

 CloseConnection();

 

 

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//下面实现下载:

 strAppName.LoadString(AFX_IDS_APP_TITLE);

 pInternetSession = new CInternetSession(strAppName,INTERNET_OPEN_TYPE_PRECONFIG);

 

 

 if(!pInternetSession)

 {

  AfxMessageBox("Can't start internet session");

 }

 

 

 CString tempRemote;

 CString tempLocal;

 CString folder;

 CString server;

 CStringArray remote;

 CStringArray local;

 CString Error;

 

 

 strUser="ABCD";           //用户名

 strPass="EFGH";         //密码

 server="192.168.1.100";    //server的IP

 tempRemote="\\dir\\1.txt";        //要下载的文件名及路径

 remote.Add(tempRemote);

 

 tempLocal = "c:\\download\\2.txt";//下载后文件名及目录

 local.Add(tempLocal);

 

 // open server

 bool conectOK;

 conectOK = OpenConnection(server);

 // transfer multiple file

 if(conectOK)

 {

  GetMultipleFile(&remote,&local,1);

 }

  

 

 // close connection

 CloseConnection();

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

实例二

---- 要联接到FTP服务器,需要两个步骤,首先必须创建一个CInternetSession对象,用类CInterSession创建并初始化一个或几个同时存在的Internet会话(session),并描述与代理服务器的连接(如果有必要的话),如果在程序运行期间需要保持与Internet的连接,可以创建一个CInternetSession对象作为类CWinApp的成员。 

---- MFC中的类CFtpConnection管理我们与Internet服务器的连接,并直接操作服务器上的目录和文件,FTP是MFC的WinInet支持的三个Internet功能之一,我们需要先创建一个CInternetSession实例和一个CFtpConnection对象就可以实现和一个FTP服务器的通信,我们不需要直接创建CFtpConnection对象,而是通过调用CInternetSession::GetFtpConnection来完成这项工作。它创建CFtpConnection对象并返回一个指向该对象的指针。 

Ftp连接类的信息 

---- 下面我们简要介绍连接类的信息 

CInternetSession对象 
---- CInternetSession(LPCTSTR pstrAgent,DWORD dwConText ,DWORD dwAccessType,LPCTSTR pstrProxyName,LPCTSTR pstrProxyBypass,DWORD dwFlags); 

---- 在创建CInternetSession对象时调用这个成员函数,CInternetSession是应用程序第一个要调用的Internet函数,它将创始化内部数据结构,以备将来在应用程序中调用。如果dwFlags包含INTERNET_FLAG_ASYNC,那末从这个句柄派生的所有的句柄,在状态回调例程注冊之前,都会出现异步状态。如果沒有打开Internet连接,CInternetSession就会抛出一个例外,AfxThorowInternetException。 

GetFtpConnection()函数 
---- CFtpConnection* CIternetSession::GetFtpConnection(LPCTSTR pstrServer,LPCTSTR pstrUserName,LPCTSTR pstrPassword,INTERNET_PORT nPort,BOOL bPassive); 

---- 调用这个函数建立一个FTP连接,并获得一个指向CFtpConnection对象的指针,GetFtpConnection连接到一个FTP服务器,创建并返回指向CFtpConnection对象的指针,它不在服务器上进行任何操作。如果打算读写文件,必须进行分步操作。关于查找,打开和读/写文件的信息需参考CFtpConnection和CFtpFileFind类。 

---- 对这个函数的调用返回一个指向CFtpConnection对象的指针。如果调用失败,检查抛出的CInternetException对象,就可以确定失败的原因。 

GetFile()函数 
---- BOOL GetFile(LPCTSTR pstrRemoteFile,LPCTSTR pstrLocalFile,BOOL bFailExists ,DWORD dwAttributes,DWORD dwFlags,DWORD dwContext); 

---- 调用这个成员函数,可以从FTP服务器取得文件,并且把文件保存在本地机器上。GetFile()函数是一个比较高级的例程,它可以处理所有有关从FTP服务器读文件,以及把文件存放在本地机器上的工作。如果dwFlags为FILE_TRANSFER_TYPE_ASCII,文件数据的传输也会把控制和格式符转化为Windows中的等阶符号。默认的传输模式是二进制模式,文件会以和服务器上相同的格式被下载。 

---- pstrRemoteFile和 pstrLocalFile可以是相对于当前目录的部分文件名,也可以是全文件名,在这两个名字中间,都既可以用反斜杠(/)或者正斜杠(/)来作为文件名的目录分隔符,GetFile()在使用前会把目录分隔符转化为适当的字符。 

---- 可以用自己选择的值来取代dwContext默认的值,设置为上下文标识符与CFtpConnection对象的定位操作有关,这个操作由CFtpConnection中的CInternetSession对象创建。返回给CInternetSession::OnStatusCallBack的值指出了所标识操作的状态。 

---- 如果调用成功,函数的返回为非0,否则返回0,如果调用失败,可以调用Win32函数GetLastError(),确认出错的原因。 

PutFile()函数 
---- BOOL PutFile(LPCTSTR pstrLocalFile, LPCTSTR pstrRemoveFile ,DWORD dwFlags, DWORD dwContext); 

---- 调用这个成员函数可以把文件保存到FTP服务器。PutFile()函数是一个比较高级的例程,它可以处理有关把文件存放到服务器上的工作。只发送数据,或要严格控制文件传输的应用程序,应该调用OpenFile和 CInternet::Write。利用自己选择的值来取代dwContext默认的值,设置为上下文标识符,上下文标识符是CInternetSession对象创建的CFtpConnection对象的特定操作有关,这个值返回给CInternetSession::OnStateCallBack,从而把操作的状态通报给它所标识的上下文。 

---- 如果调用成功,函数的返回为非0,否则返回0,如果调用失败,可以调用Win32函数GetLastError(),确认出错的原因。 

连接到FTP站点 

---- 建立连接到ftp.microsoft.com的程序,它是一个单文档程序。并且连接由视图类的构造函数完成。 

建立单文档程序ftp 

在ftpview.h中加入包含#include < afxinet.h > 

在ftpview.h中添加如下的成员变量 
public: 
CInternetSession *m_pInetSession; 
CFtpConnection *m_pFtpConnection; 

在ftpview.cpp中的ftpview构造函数中加入下面的代码 
CFtpView::CFtpView() 

m_pInetSession=new CInternetSession 
(AfxGetAppName(),1, 
PRE_CONFIG_INTERNET_ACCESS); 
try 

m_pFtpConnection=m_pInetSession-> 
GetFtpConnection("FTP.MICROSOFT.COM"); 

catch(CInternetException *pEx) 

TCHAR szError[1024]; 
if(pEx->GetErrorMessage(szError,1024)) 
AfxMessageBox(szError); 
else 
AfxMessageBox("There was an exception"); 
pEx->Delete(); 
m_pFtpConnection=NULL; 



在ftpview.cpp中的ftpview析构函数中加入下面的代码 
CFtpView::~CFtpView() 

if(m_pFtpConnection!=NULL) 

m_pFtpConnection->Close(); 
delete m_pFtpConnection; 

delete m_pInetSession; 


编译并且执行程序,如果连接出现问题,将会在一个消息框中报告出错消息。 
发送文件到FTP文件服务器 

---- 创建一个发送文件到FTP文件服务器的程序 

建立单文档程序ftpfw, 在ftpfwview.h中加入包含 #include < afxinet.h > 

在ftpfwview.h中添加如下的成员变量 
public: 
bool m_bConnectionAttempted; 
int m_nFileStatus; 

在ftpview.cpp中的ftpview构造函数中加入下面的代码 
CFtpfwView::CFtpfwView() 

m_bConnectionAttempted=false; 


使用ClassWizard加入新的类CFtpThread,该类派生于CWinThread 在ftpthread.h中加入如下变量 
public: 
static UINT PutFile(LPVOID Status); 

添加新类成员函数代码 
UINT CFtpThread::PutFile(LPVOID Status) 

int *pnFileStatus; 
CInternetSession *pInetSession; 
CFtpConnection *pFtpConnection=NULL; 
pnFileStatus=(int *)Status; 
*pnFileStatus=0; 
pInetSession=new 
CInternetSession(AfxGetAppName(),1, 
PRE_CONFIG_INTERNET_ACCESS); 
try 

pFtpConnection=pInetSession-> 
GetFtpConnection("192.34.45.0"); 

catch(CInternetException *pEx) 

pEx->Delete(); 
pFtpConnection=NULL; 
*pnFileStatus=-1; 
goto BallOut; 

*pnFileStatus =1; 
pFtpConnection->Remove("test.txt"); 
if(!pFtpConnection->PutFile 
("test.txt","test.txt")) 
*pnFileStatus=-2; 
else 
*pnFileStatus=2; 
BallOut: 
if(pFtpConnection!=NULL) 

pFtpConnection->Close(); 
delete pFtpConnection; 

delete pInetSession; 
AfxEndThread(0); 
return false; 


编辑ftpfwview.cpp中的OnDraw()函数 
void CFtpfwView::OnDraw(CDC* pDC) 

CFtpfwDoc* pDoc = GetDocument(); 
ASSERT_VALID(pDoc); 
if(!m_bConnectAttempted) 

m_bConnectAttempted=TRUE; 
AfxBeginThread((AFX_THREADPROC) 
CFtpThread::PutFile,&m_nFileStatus); 



编译并且执行程序,在连接和传输的过程中,应用程序仍然可以作自己的工作,这是因为传输的过程发生在线程中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: