QFtp在使用上與 QHttp 非常類似,只不過FTP機制比HTTP來得更為複雜一些,所以QFtp上可以進行的相關操作更為豐富,以下先製作一個簡單的程式,使用QFtp進行FTP檔案下載,首先是FtpGet的定義:
#ifndef FTPGET_H #define FTPGET_H
#include <QObject>
class QUrl; class QFtp; class QFile;
class FtpGet : public QObject { Q_OBJECT
public: FtpGet(QObject *parent = 0); void downloadFile(const QUrl &url); signals: void finished(); private slots: void done(bool error); private: QFtp *ftp; QFile *file; };
#endif
定義上與上一個QHttp故意設計的類似,基本上實作也非常接近:
#include <QtNetwork> #include <QFile> #include <iostream> #include "FtpGet.h" using namespace std;
FtpGet::FtpGet(QObject *parent) : QObject(parent) { ftp = new QFtp(this); connect(ftp, SIGNAL(done(bool)), this, SLOT(done(bool))); }
void FtpGet::downloadFile(const QUrl &url) { QFileInfo fileInfo(url.path()); QString fileName = fileInfo.fileName();
file = new QFile(fileName); if (!file->open(QIODevice::WriteOnly)) { cerr << "Unable to save the file" << endl; delete file; file = 0; return; } ftp->setTransferMode(QFtp::Passive); ftp->connectToHost(url.host(), url.port(21)); ftp->login("user", "passwd"); ftp->get(url.path(), file); ftp->close(); }
void FtpGet::done(bool error) { if (error) { cerr << "Error: " << qPrintable(ftp->errorString()) << endl; } else { cerr << "File downloaded as " << qPrintable(file->fileName()) << endl; } file->close(); delete file; file = 0; emit finished(); }
您可以使用QFtp的setTransferMode()來設定傳送模式,例如上面的程式設定為被動(Passive)模式,要連接至伺服器,使用connectToHost()方法,要登入則使用login()方法,下載檔案使用get()(上傳則使用put())等,接下來寫個簡單的測試程式:
#include <QCoreApplication> #include <QUrl> #include "FtpGet.h" #include <iostream> using namespace std;
int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); FtpGet getter; getter.downloadFile( QUrl("ftp://caterpillar.onlyfun.net/public_html/index.html")); QObject::connect(&getter, SIGNAL(finished()), &app, SLOT(quit())); return app.exec(); }
在Qt的說明文件中,有個 FTP Example 範例,您可以參考當中的程式,了解更多有關QFtp的使用方式。
|
|