qt4使用QFtp实现ftp文件同步下载实例

本文提供了一个qt4.8下利用QFtp封装的一个文件同步下载的例子。

ftpclient.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#ifndef FTPCLIENT_H
#define FTPCLIENT_H

#include <QObject>
#include <QFtp>
#include <QFile>

class FtpClient : public QObject
{
Q_OBJECT
public:
explicit FtpClient(QObject *parent = 0);
bool getFile(QString path, QString name, QString localPath);
void setHost(QString ip, int port=21);
void setLogin(QString username, QString password);

signals:
void getFileDoneSignal();

public slots:
void getFileDoneSlot(bool err);
private:
QFile file;
QFtp ftp;
bool ftpFlag;
private:
QString ip;
int port;
QString username;
QString password;
};

#endif // FTPCLIENT_H

ftpclient.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "ftpclient.h"
#include <QDir>
#include <QEventLoop>

FtpClient::FtpClient(QObject *parent) : QObject(parent)
{
connect(&ftp, SIGNAL(done(bool)), this, SLOT(getFileDoneSlot(bool)));
}

bool FtpClient::getFile(QString path, QString name, QString localPath)
{
QDir dir;
if (!dir.exists(localPath)) {
dir.mkpath(localPath);
}
file.setFileName(localPath+"/"+name);
if (!file.open(QIODevice::WriteOnly)) {
return false;
}
ftp.connectToHost(ip, port);
ftp.login(username, password);
ftp.cd(path);
ftp.get(name, &file);
ftp.close();
QEventLoop loop;
connect(this, SIGNAL(getFileDoneSignal()), &loop, SLOT(quit()));
loop.exec();
return ftpFlag;
}

void FtpClient::setHost(QString ip, int port)
{
this->ip = ip;
this->port = port;
}

void FtpClient::setLogin(QString username, QString password)
{
this->username = username;
this->password = password;
}

void FtpClient::getFileDoneSlot(bool err)
{
file.close();
if (err) {
ftpFlag = false;
}
else {
ftpFlag = true;
}
emit getFileDoneSignal();
}