因项目需要,利用MFC写了一个客户端,实现远程文件的上传,下载,删除等功能。
服务器用的是免费的Home Ftp Server。首先简单介绍一下CInternetSession类和CFtpConnection类,他们包含在afxinet.h头文件中,是MFC中对连接FTP服务器功能的一个封装。
主界面:
一.连接过程
void CMFCApplication2Dlg::ConnectFtp()//连接FTP
{
UpdateData(TRUE);
user_name = m_user;
pass_word = m_password;
ftp_ip = m_ip;
ftp_port = m_port;
UpdateData(FALSE);
pInternetSession = new CInternetSession(AfxGetAppName(), 1, PRE_CONFIG_INTERNET_ACCESS);
//利用Internet会话对象pInternetSession打开一个FTP连接
try
{
pFtpConnection = pInternetSession->GetFtpConnection(ftp_ip, user_name, pass_word, 21, TRUE);
//AfxMessageBox(L"Connect successfully");
}
catch (CInternetException *pEx)
{
TCHAR szError[1024];
if (pEx->GetErrorMessage(szError, 1024))
{
AfxMessageBox(szError);
}
else
{
AfxMessageBox(_T("There was an exception in FTP"));
}
pEx->Delete();
pFtpConnection = NULL;
}
}
二.断开过程
void CMFCApplication2Dlg::OnBnClickedDisconnectButton()//断开
{
// TODO: 在此添加控件通知处理程序代码
if (NULL != pFtpConnection)
{
pFtpConnection->Close();
pFtpConnection = NULL;
pInternetSession->Close();
pInternetSession = NULL;
m_list.ResetContent();
m_list.AddString(_T("连接已经断开!"));
GetDlgItem(IDC_IP_EDIT)->EnableWindow(TRUE);
GetDlgItem(IDC_PORT_EDIT)->EnableWindow(TRUE);
GetDlgItem(IDC_PASSWORD_EDIT)->EnableWindow(TRUE);
GetDlgItem(IDC_USER_EDIT)->EnableWindow(TRUE);
GetDlgItem(IDC_CONNECT_BUTTON)->EnableWindow(TRUE);
GetDlgItem(IDC_CHECK1)->EnableWindow(TRUE);
}
}
三.文件上传
if (NULL != pFtpConnection)
{
CString str;
CString strname;
//弹出“打开”对话框
CFileDialog file(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("所有文件(*.*)|*.*|"), this);
if (file.DoModal() == IDOK)
{
str = file.GetPathName();
strname = file.GetFileName();
}
if (bconnect)
{
CString strdir;
pFtpConnection->GetCurrentDirectory(strdir);
//上传文件
BOOL bput = pFtpConnection->PutFile((LPCTSTR)str, (LPCTSTR)strname);
if (bput)
{
pInternetSession->Close();//关闭会话
this->ConnectFtp();//重新连接保持持续会话
pFtpConnection->SetCurrentDirectory(strdir);
this->UpdateDir();//更新目录列表
AfxMessageBox(_T("上传成功!"));
}
}
}
四.文件下载
void CMFCApplication2Dlg::OnBnClickedDownloadButton()//下载文件
{
// TODO: 在此添加控件通知处理程序代码
if (NULL != pFtpConnection)
{
CString selfile;
m_list.GetText(m_list.GetCurSel(), selfile);//获取用户选择要下载的资源名
if (!selfile.IsEmpty())
{
//弹出“另存为”对话框
CFileDialog file(FALSE, NULL, selfile, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("所有文件(*.*)|*.*|"), this);
if (file.DoModal() == IDOK)
{
CString strname;
strname = file.GetPathName();
CString strdir;
pFtpConnection->GetCurrentDirectory(strdir);
pFtpConnection->GetFile(selfile, strname);//下载文件到选定的本地位置
pInternetSession->Close();//关闭废弃的对话
this->ConnectFtp();//保持持续会话
pFtpConnection->SetCurrentDirectory(strdir);
this->UpdateDir();//更新目录列表
AfxMessageBox(_T("下载成功!"));
}
}
}
}