使用 QNetworkAccessManager 能夠實現 Ftp 的上傳/下載功能,但它沒有提供例如list、cd、remove、mkdir、rmdir、rename 等功能。這種狀況下,咱們可使用QFtp,須要下載源碼、編譯並處理一些坑。git
從 GitHub 下載 QFtp:github
https://github.com/qt/qtftp
用qtcreator打開qftp/qftp.pro,編譯生成庫文件。架構
我以Qt5.5.1爲例說明,其它版本相似函數
#include "qftp.h"
。CONFIG(debug, debug|release) { LIBS += -lQt5Ftpd } else { LIBS += -lQt5Ftp }
也就是說,ftp的加載方式還不能與Qt5的原生庫徹底一致,如何作到這一點,我還須要時間研究。測試
修正進度條的提早顯示,對progressDialog新對象進行以下設置,去掉了取消操做,取消操做有問題,暫時屏蔽。ui
progressDialog = new QProgressDialog("download...", nullptr, 0, 100, this); progressDialog->setWindowModality(Qt::WindowModal); auto winFlags = windowFlags() & ~Qt::WindowMinMaxButtonsHint; progressDialog->setWindowFlags(winFlags &~ Qt::WindowCloseButtonHint); //去掉窗口的默認按鈕 progressDialog->reset(); //避免提早顯示 progressDialog->setAutoClose(false); progressDialog->setAutoReset(false);
屏蔽取消按鈕的消息連接。this
//connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
支持多文件下載
首先,在QTreeWidget生成後,設置其能夠選中多行。url
fileList->setSelectionMode(QAbstractItemView::ExtendedSelection);
修改downloadFile函數,支持多文件下載。命令行
QList<QTreeWidgetItem*> selectedItemList = fileList->selectedItems(); for (int i = 0; i < selectedItemList.size(); i++) { QString fileName = selectedItemList[i]->text(0); if (QFile::exists(fileName)) { QMessageBox::information(this, tr("FTP"), tr("There already exists a file called %1 in the current directory.").arg(fileName)); return; } file = new QFile(fileName); if (!file->open(QIODevice::WriteOnly)) { QMessageBox::information(this, tr("FTP"), tr("Unable to save the file %1: %2.").arg(fileName).arg(file->errorString())); delete file; return; } ftp->get(fileName, file); progressDialog->setLabelText(tr("Downloading %1...").arg(fileName)); downloadButton->setEnabled(false); progressDialog->exec(); }
https://github.com/zhoutk/qtDemo
git clone https://github.com/zhoutk/qtDemo cd qtDemo/qftp & mkdir build & cd build cmake .. cmake --build .
編譯時注意:cmake默認爲x86架構,須要與你安裝的Qt版本對應;編譯好了,運行前,請注意目錄結構是否正確。debug
上面是正統方法在qt5中使用qftp,還能夠直接把其源代碼歸入你的應用項目中,由於一共只有四個文件,稍做修改就可使用。我發現該項目的問題,主要是cancelDownload會出讓程序崩潰,感受問題出在本地文件已經被清除,還有後續的數據到來,結果就異常了。有時間再來研究,看能不能把協議學透,本身造個輪子出來。