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))); 然后在槽函數內的elseif(ftp->currentCommand()==QFtp::Get)這個分句內將file關閉。2、ftp->list()調用之后,對于找到的每個文件和目錄,都會發出 listInfo()信號三、QFtp的一些其他功能
在連接并登錄服務器之后才能進行下列操作1、實現文件上傳,此時的file不需要打開 file=newQFile("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
新聞熱點
疑難解答