我想使用QFtp上传一个文本文件到FTP服务器。
这是我的代码:
QFile *file = new QFile("test.txt");
QFtp *ftp = new QFtp();
if(file->open(QIODevice::ReadWrite)) {
ftp->setTransferMode(QFtp::Active);
ftp->connectToHost(server);
ftp->login(name, password);
ftp->put(file, "test.txt");
ftp->close();
}执行此代码后,我在ftp服务器上看不到任何内容。当我查看QFtp::put的文档时,我发现第一个参数应该是QIODevice或QByteArray。我该怎么做呢?
编辑:
所以我现在有了这个代码:
//ftp.cpp
QFile *file = new QFile("test.txt");
QFtp *ftp = new QFtp();
this->connect(ftp, SIGNAL(commandStarted(int)), SLOT(ftpCommandStarted(int)));
this->connect(ftp, SIGNAL(commandFinished(int, bool)), SLOT(ftpCommandFinished(int, bool)));
this->connect(ftp, SIGNAL(done(bool)), SLOT(ftpDone(bool)));
this->connect(ftp, SIGNAL(dataTransferProgress(qint64, qint64)), SLOT(ftpDataTransferProgress(qint64, qint64)));
this->connect(ftp, SIGNAL(stateChanged(int)), SLOT(ftpStateChanged(int)));
if(file->open(QIODevice::ReadWrite)) {
ftp->setTransferMode(QFtp::Active);
ftp->connectToHost(server);
ftp->login(name, password);
ftp->put(file, "test.txt");
ftp->close();
}使用这些函数:
//ftp.h
void ftpCommandStarted(int id);
void ftpCommandFinished(int id, bool error);
void ftpDone(bool);
void ftpDataTransferProgress(qint64, qint64);
void ftpStateChanged(int);
//ftp.cpp
void EmailDialog::ftpCommandStarted(int id) {
this->messageBox("Command Started: " + QString::number(id));
}
void EmailDialog::ftpCommandFinished(int id, bool error) {
this->messageBox("Command Finished: " + QString::number(id) + " Error: " + (error ? "Error" : "No Error"));
}
void EmailDialog::ftpDone(bool error) {
this->messageBox("Done " + QString(error ? "Error" : "No Error"));
}
void EmailDialog::ftpDataTransferProgress(qint64 done, qint64 total) {
this->messageBox("Done: " + QString::number(done) + " Total: " + QString::number(total));
}
void EmailDialog::ftpStateChanged(int state) {
QString text;
switch (state) {
case 0:
text = "QFtp::Unconnected";
break;
case 1:
text = "QFtp::HostLookup";
break;
case 2:
text = "QFtp::Connecting";
break;
case 3:
text = "QFtp::Connected";
break;
case 4:
text = "QFtp::LoggingIn";
break;
case 5:
text = "QFtp::Closing";
break;
default:
text = "";
break;
}
this->messageBox(text);
}但是,我没有得到任何指示,表明正在调用插槽。我没有弹出任何消息框。我在这里做错了什么?
发布于 2011-12-24 00:49:18
您拥有的代码片段看起来是正确的(尽管还没有尝试编译它),所以问题可能出在该代码片段之外的某个地方。
作为对另一个答案的响应,您不需要捕获信号来执行代码。调用put、close等,将对这些命令进行排队,当它们准备就绪时,无论您是否连接到信号,它们都将运行。请参考docs中的详细说明。话虽如此,我强烈建议连接到信号,因为这是你为你的用户和调试获得反馈的方式。
至于为什么你当前的代码不能工作,我会问的最常见的问题是:
这些都是我能想到的基本问题。祝好运!
发布于 2011-12-20 00:02:39
QFtp类以异步方式传输数据。因此,顺序调用connecToHost、put、error、currentCommand和close函数将永远不会实际执行任何命令。你需要做的是编写一个类,这样你就可以使用信号和槽了。在你开始传输之后捕捉信号是关键。QFtp详细描述中列出的示例对您的问题进行了一些说明/
https://stackoverflow.com/questions/8563928
复制相似问题