刚做完的项目中,有个远程升级的功能是通过FTP服务器实现的,总结一下遇到知识点。
首先要搭建一个FTP服务器,网上可以找到很多软件,我用的是server-u,方便简单。设置完毕后,要修改FTP用户权限(默认只是读取),可增加写入、删除等权限。
这时可以用dos命令进行简单的测试,dos窗口输入:1.ftp;2.open 127.0.0.1 2121(端口号),ftp默认端口为21,可以省去,其他端口都不可以省略。然后输入用户名和密码就可以登录。通过bin、put、get可以上送、下载文件了。一般用bin模式较为安全些。也可以通过页面方式 进行测试 如 ftp:\\127.0.0.1:2121 的方式登录。
下面是vc实现ftp服务的下载和上送资料:
第一步:声明对象并初始化
CInternetSession *pInternetSession;
CFtpConnection *pFtpConnection;
成员函数实现初始化
// get the name of the app
int iRet = strAppName.LoadString(AFX_IDS_APP_TITLE);
// create an internet session
pInternetSession = new CInternetSession(strAppName,
INTERNET_OPEN_TYPE_PRECONFIG);
析构函数
pInternetSession->Close();
// delete the session
if(pInternetSession != NULL)
delete pInternetSession;
pInternetSession->Close();
// delete the session
if(pInternetSession != NULL)
delete pInternetSession;
第二步:连接FTP服务器 server(IP)
pFtpConnection = pInternetSession->GetFtpConnection(server,
strUser,strPass, port, FALSE);
第三步:下载文件 两个参数,FTP文件目录+文件名、本机下载目录+文件名
// Try to get the file
BOOL bGotFile = pFtpConnection->GetFile(remoteFile,
localFile,FALSE,FILE_ATTRIBUTE_NORMAL,
FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE);
第四步:上传文件 (注:FTP服务器一定要允许上传文件),两个参数,本机下载目录+文件名、FTP文件目录+文件名
BOOL bPutFile = pFtpConnection->PutFile(pstrLocalFile, pstrRemoteFile);
通过以上操作,便可以实现简单的FTP上传、下载文件了。
BOOL bPutFile = pFtpConnection->PutFile(pstrLocalFile, pstrRemoteFile);