由于工作需要,需要实现一个ftp日志查看工具。发现QFtp刚好符合要求,以下是部分实现,附带源码。
QFtp信号连接:
void MonitorLogWidget::InitFtpManager()
{
ftp = new MonitorLog::QFtp;
QObject::connect(ftp, &MonitorLog::QFtp::listInfo, this, &MonitorLogWidget::addToList);
connect(ftp, SIGNAL(commandStarted(int)), this, SLOT(ftpCommandStarted(int)));
connect(ftp, SIGNAL(commandFinished(int, bool)), this, SLOT(ftpCommandFinished(int, bool)));
connect(ftp, SIGNAL(stateChanged(int)), this, SLOT(ftpStateChanged(int)));
Connect();
}
日志文件列表实现:
void MonitorLogWidget::addToList(const MonitorLog::QUrlInfo& urlInfo)
{
double dFileSize = ((int)(urlInfo.size() / 1024.0 * 100)) / 100.0;
QString fileSize = QString::number(dFileSize, 'g', 10) + "KB";
QStandardItem *item00 = new QStandardItem(urlInfo.name());
QStandardItem *item10 = new QStandardItem(fileSize);
static int irow = 0;
QList<QStandardItem*> itemL;
itemL.push_back(item00);
itemL.push_back(item10);
standardModel->insertRow(irow, itemL);
}
文件加载实现:
void MonitorLogWidget::ftpCommandFinished(int, bool error)
{
if (ftp->currentCommand() == MonitorLog::QFtp::ConnectToHost){
if (error)
{
ui.label->setText("ConnectToHost error");
}
else
{
ui.label->setText("ConnectToHost successful");
}
}
else if (ftp->currentCommand() == MonitorLog::QFtp::Login){
if (error)
{
ui.label->setText("Login error");
}
else
{
ui.label->setText("Login successful");
}
}
else if (ftp->currentCommand() == MonitorLog::QFtp::Get){
if (error)
{
ui.label->setText(QString::fromLocal8Bit("加载文件失败"));
}
else{
QByteArray data;
data = ftp->readAll();
QTextCodec *codec = QTextCodec::codecForName("GBK");
QString utf8String = codec->toUnicode(data);
QByteArray utf8Data = utf8String.toUtf8();
ui.textEdit->append(utf8Data.constData());
ui.label->setText(QString::fromLocal8Bit("加载成功"));
}
}
else if (ftp->currentCommand() == MonitorLog::QFtp::List){
ui.label->setText("List is empty");
}
else if (ftp->currentCommand() == MonitorLog::QFtp::Close){
ui.label->setText("closed");
}
}