参考:http://blog.sina.com.cn/s/blog_5cf5e7c40100vc9p.html
第一步
在你的头文件中添加以下表达式.
#include < afxinet.h >
第二步
在你的头文件中,添加以下变量
CFtpConnection *m_pFtpConnection;
CInternetSession m_Session;
第三步
在你初始化应用程序的时候(OnInitDialog or InitInstance functions),添加上下面几行
m_pFtpConnection = NULL;
try
{
//这里用你的用户名,密码连接到ftp服务器 ,其中usr是用户名,pwd是密码,ftpSite.com
// 是你想要连接的ftp服务器.
m_pFtpConnection = m_Session.GetFtpConnection("ftpSite.com","usr","pwd",
INTERNET_INVALID_PORT_NUMBER);
}
catch(CInternetException *pEx)
{
pEx->ReportError(MB_ICONEXCLAMATION);
m_pFtpConnection = NULL;
pEx->Delete();
}
return TRUE;
第四步
为了上传文件,添加上一下几行代码:-
CFileFind Finder;
CString strFileName;
// 这里c:\\Myfile.bmp 是你要上传的文件名称
// 文件没有必要是一个bmp图片,你可以根据需要上传任何图片
// CString strFileName 确保上传到服务器上的文件保持原来的名称,当然,你也可以改成任何其他的
// 名称
if(Finder.FindFile("C:\\Myfile.bmp")==TRUE)
{
Finder.FindNextFile();
strFileName = Finder.GetFileName();
Finder.Close();
}
BOOL bUploaded = m_pFtpConnection->PutFile("C:\\Myfile.bmp",strFileName,
FTP_TRANSFER_TYPE_BINARY,1);
AfxMessageBox("Uploaded Successfully");
第五步
添加以下几行代码,可以下载一个文件.
第一个参数表示服务器上的文件名称 第二个参数表示你要存放在本地的路径.
m_pFtpConnection->GetFile("File.ext","C:\\File.ext",TRUE,
FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_BINARY,1);
例如:CFileDialog dlg(FALSE, "wav", selectedFile, NULL, "语音文件(*.wav)|*.wav|All Files (*.*)|*.*||");
if (dlg.DoModal() == IDOK)
{
CString strFilePath = dlg.GetPathName();
if ( (GetFileAttributes( strFilePath) != -1) )
{
CString strQuery;
strQuery.Format("%s 已经存在,要替换它吗?", strFilePath);
if ( IDNO == ::MessageBox(m_hWnd, strQuery, "文件覆盖询问", MB_ICONQUESTION | MB_YESNO) )
{
return;
}
}
m_pFtpConnection->GetFile(selectedFile,strFilePath,TRUE,FILE_ATTRIBUTE_NORMAL,FTP_TRANSFER_TYPE_BINARY,1);
}
第六步
关闭连接
m_Session.Close();
m_pFtpConnection->Close();
if(m_pFtpConnection!=NULL)
delete m_pFtpConnection;
FTP目录遍历函数
CList<CString> m_listRecordName;
void CRecordDialog::GetFilesList()
{
CFtpFileFind finder(m_pFtpConnection);
BOOL bWorking = finder.FindFile(NULL);
CList<CString> listDir;
while (bWorking)
{
bWorking = finder.FindNextFile();
if (finder.IsDots() || finder.IsHidden())
{
continue;
}
if (!finder.IsDirectory())
{
// 根据需要保存地址或做其他操作,这里保存的是文件名
//fileList.push_back(finder.GetFilePath().operator LPCTSTR());
m_listRecordName.AddHead(finder.GetFileName());
continue;
}
else
{
// 保存目录
listDir.AddHead(finder.GetFilePath());
}
}
// 这个需要关闭,只能有一个CFtpFileFind,如果没有这句,将只能获得一部分文件地址
finder.Close();
// 遍历目录
POSITION pos = listDir.GetHeadPosition();
while(pos != NULL)
{
CString dir = listDir.GetNext(pos);
m_pFtpConnection->SetCurrentDirectory(dir);
GetFilesList();
}
}