事先搭建FTP服务器,上传下载端口
新建MFC基于对话框程序,添加上传下载按钮。
上传按钮
CInternetSession * pInternetSession = NULL;
CFtpConnection* pFtpConnection = NULL;
//建立连接
pInternetSession = new CInternetSession(AfxGetAppName());
//服务器的ip地址
CString strADddress = "192.168.119.1";
//用户名与密码
CString strUserName = "cgs";
CString strPwd = "a12345";
//服务器的目录
CString strDir = "\\"; //若要设置为服务器的根目录,则使用"\\"就可 这个目录是你ftp里面的文件夹目录
//创建了一个CFtpConnection对象,之后就可以通过这个对象进行上传文件,下载文件了
pFtpConnection = pInternetSession->GetFtpConnection(strADddress, strUserName, strPwd);
//设置服务器的目录
bool bRetVal = pFtpConnection->SetCurrentDirectory(strDir);
if(bRetVal == false)
{
AfxMessageBox("目录设置失败");
return ;
}
else
{
//把本地文件上传到服务器上
CString strLocalFile = "D:\\ftp.txt";
CString strRemoteFile = "abc.txt";
pFtpConnection->PutFile(strLocalFile, strRemoteFile);
}
//释放资源
if(NULL != pFtpConnection)
{
pFtpConnection->Close();
delete pFtpConnection;
pFtpConnection = NULL;
}
if(NULL != pInternetSession)
{
delete pInternetSession;
pInternetSession = NULL;
}
下载按钮
CInternetSession* pInternetSession = NULL;
CFtpConnection* pFtpConnection = NULL;
//建立连接
pInternetSession = new CInternetSession(AfxGetAppName());
//服务器的ip地址
//若要设置为服务器的根目录,则使用"\\"就可以了
//创建了一个CFtpConnection对象,之后就可以通过这个对象进行上传文件,下载文件了
pFtpConnection = pInternetSession->GetFtpConnection("192.168.119.1", "cgs", "a12345");
//设置服务器的目录
bool bRetVal = pFtpConnection->SetCurrentDirectory("\\");
if(bRetVal == false)
{
AfxMessageBox("目录设置失败");
return ;
}
else
{
pFtpConnection->GetFile("abc.txt", "D:\\a.txt");
}
//释放源
if(NULL != pFtpConnection)
{
pFtpConnection->Close();
delete pFtpConnection;
pFtpConnection = NULL;
}
if(NULL != pInternetSession)
{
delete pInternetSession;
pInternetSession = NULL;
}