编译好QFtp之后(点击打开链接),用QFtp实现下载功能
一、使用windows本机搭建好FTP服务器
参照:windows如何搭建FTP服务器
搭建好服务器是关键,搭建完之后才有下面的操作。
ftp->connectToHost("192.168.0.104", 21); // 主机:192.168.0.104 端口号:21这个 192.168.0.104是本机ip地址,本机ip地址如果变动了需要重新按照搭建服务器的过程设定服务器的ip地址
可以在浏览器里输入
ftp://192.168.0.104/然后回车看下能否打开
下面是我的服务器的本地物理路径
二、实现FTP下载功能和显示服务器文件信息
#include "dialog.h"
#include "ui_dialog.h"
#include <QDebug>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
ftp = new QFtp(this);
connect(ftp, SIGNAL(commandFinished(int,bool)),this, SLOT(slotftpCommandFinished(int,bool)));
connect(ftp, SIGNAL(listInfo(const QUrlInfo &)),this, SLOT(slotShowList(const QUrlInfo &)));
ftp->connectToHost("192.168.0.111", 21); // 主机:192.168.0.111 端口号:21
ftp->login("wang", "123456"); // 用户名:wang 密码:123456
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_downButton_clicked()//下载
{
file = new QFile("d:/main.cpp");
if (!file->open(QIODevice::WriteOnly))
{
file->remove();
delete file;
file = NULL;
} else {
ftp->get("main.cpp", file); //下载服务器的main.cpp
}
}
void Dialog::slotftpCommandFinished(int, bool error)
{
if (ftp->currentCommand() == QFtp::ConnectToHost)
{
if (error)
{
}
return;
}
else if (ftp->currentCommand() == QFtp::Login)
{
}
else if (ftp->currentCommand() == QFtp::Get)
{
if (error)
{
file->close();
file->remove();
}
else
{
file->close();//核心代码,必不可少
}
delete file;
}
else if (ftp->currentCommand() == QFtp::List)
{
}
}
void Dialog::on_listButton_clicked()
{
ftp->list();//对于找到的每个目录条目,都会发出 listInfo()信号
}
void Dialog::slotShowList(const QUrlInfo &urlInfo)
{
qDebug() << urlInfo.name() << urlInfo.size() << urlInfo.owner() << urlInfo.group()
<< urlInfo.lastModified().toString("MMM dd yyyy") << urlInfo.isDir();
}
注意事项:
1、很多人下载文件失败,是由于file->open()了,但是下载完之后,file没有close,但是由于ftp->get()又是异步的,不能在调用之后立马将file关闭
所以需要
connect(
ftp
,
SIGNAL
(commandFinished(
int
,
bool
)),
this
,
SLOT
(slotftpCommandFinished(
int
,
bool
))); 然后在槽函数内的
else
if
(
ftp
->currentCommand()
==
QFtp
::
Get
)这个分句内将file关闭。
2、
ftp
->list()调用之后,对于找到的每个文件和目录,都会发出 listInfo()信号
三、QFtp的一些其他功能
在连接并登录服务器之后才能进行下列操作
1、实现文件上传,此时的file不需要打开
file
=
new
QFile
(
"d:/main.cpp"
);
ftp
->put(
file
,
"main.cpp"
);
2、创建文件夹
ftp
->mkdir(
"new_dir"
);
3、删除文件/目录
remove() 是删除文件,rmdir() 则是删除目录。
4、切换工作目录
ftp->
cd
(
"/doc"
);//doc是根目录下的文件夹
5、对服务器上的文件进行重命名
ftp
->
rename
(
"c++"
,
"c"
);
// c++ -> c
参照博客:http://blog.csdn.net/liang19890820/article/details/53318906#comments