在Qt的說明文件中,已有QFtp的使用範例,
但是該範例並沒有介紹put(),本文便會簡單的介紹put()的使用方法。
1.建立ftp通道
使用以下指令便可以連結到想要的ftp server
m_pftp = new QFtp(this); m_pftp->connectToHost("127.0.0.1"); m_pftp->login("USER", "PASSWORD");
※"127.0.0.1"為ftp server的ip,當然也可以是domain name
※"USER"及"PASSWORD"分別為使用者的帳號和密碼
2.使用put方法上傳檔案
在這邊我的做法是將欲上傳的檔案路徑都放在m_slUploadList這個QStringList變數中,再配合QFile與put()來上傳檔案。
if(m_pftp->state() == QFtp::LoggedIn) { int iLoop = m_slUploadList.count(); for(int index = 0; indexopen(QFile::ReadOnly); m_pftp->put(pFile, GetFileName(m_slUploadList[index])); } }
其中
if(m_pftp->state() == QFtp::LoggedIn)
這一行是在確定程式已經登入ftp中,不知為何若是將這個判斷是直接寫在 m_pftp->login("USER", "PASSWORD");這個指令之後,會造成這個if判斷為false,猜想應該是ftp需要一些登入的時間,所以如果一登入就進行判斷的話,會因為程式仍未登入ftp而判斷成false的情形。
m_pftp->put(pFile, GetFileName(m_slUploadList[index]));
因為m_slUploadList[index]裡面是存著路徑+檔名,所以需要另外一個函式來取出檔名,在這邊就野人獻曝順便提供一下GetFileName()的內容吧!
QString GetFileName(QString NameWithPath) { int iLast = NameWithPath.lastIndexOf("/"); QString strFileName; strFileName = NameWithPath.mid(iLast+1); return strFileName; }