我遇到了将文件两次上传到服务器的问题。
我在Windows XP上使用C ++ Qt的QFileSystemWatcher类在文件夹更改时发送文件文件很小(1-12kb)。
应用程序通过扫描文件夹发送文件(在directoryChanged信号上),循环浏览文件并发送我需要的文件。服务器使用xml文件进行响应,该文件返回到同一文件夹中以供另一个应用程序处理。
显然正在发生的事情是,在某些系统上,几乎同时有2个非常快速的目录变化信号,并且发生了两次非常快速的文件上传。
服务器正在运行Apache和PHP,并且在PHP方面有一个简单的MUTEX,但我只想找到问题的根源,这似乎是在Qt方面。 我愿意使用另一个类,另一个库或直接使用C ++。
以下是一些代码,我删除了所有不相关的内容:
this->w = new QFileSystemWatcher();
this->w->addPath("C:/POSERA/MaitreD/DATA/INT");
QStringList directoryList = w->directories();
Q_FOREACH(QString directory, directoryList)
{
qDebug() << "Watching Main Directory name: " << directory << endl;
}
DirectoryWatcher* dw = new DirectoryWatcher;
QObject::connect( this->w, SIGNAL(directoryChanged(const QString&)),
dw, SLOT(directoryChanged(const QString&)));
和DirectoryWatcher.cpp:
DirectoryWatcher::DirectoryWatcher(QWidget* parent) : QWidget(parent)
{
lockSend = false;
}
void DirectoryWatcher::directoryChanged(const QString& str)
{
directoryLastChanged = str;
QByteArray byteArray = str.toUtf8();
const char* cString = byteArray.constData();
sendChangedFiles(cString);
}
void DirectoryWatcher::sendChangedFiles(const char* path)
{
DIR *dir;
struct dirent *ent;
if ((dir = opendir (path)) != NULL)
{
QString str;
while ((ent = readdir (dir)) != NULL)
{
str = QString("%1/%2").arg(path, ent->d_name);
QFileInfo info(str);
if (lockSend == false &&
(info.completeSuffix() == "xml" || info.completeSuffix() == "XML") &&
(info.baseName() != "") &&
(!info.baseName().startsWith("REDM")) &&
(!info.baseName().startsWith("REFT")))
{
// reset the counter.
this->resendCounter = 0;
sendFileAndAccept(str.toUtf8().constData());
}
}
closedir (dir);
}
else
{
qDebug() << "Could not open directory" << endl;
}
}
class QNetworkRequest;
class QNetworkReply;
void DirectoryWatcher::sendFileAndAccept(const char* path)
{
// increment the resend counter
this->resendCounter++;
QFileInfo fileInfo(path);
QNetworkAccessManager * mgr = new QNetworkAccessManager(this);
connect(mgr,SIGNAL(finished(QNetworkReply*)),
this,SLOT(saveResponse(QNetworkReply*)));
connect(mgr,SIGNAL(finished(QNetworkReply*)),
mgr,SLOT(deleteLater())); // @todo delete later
QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
QHttpPart filePart;
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("text/xml")); // @todo test
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"someFile\"; filename=\"" + fileInfo.baseName() + ".xml\""));
currentFileSent = fileInfo.baseName();
QFile *file = new QFile(path);
file->open(QIODevice::ReadOnly);
filePart.setBodyDevice(file);
file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
multiPart->append(filePart);
// POST request
QNetworkReply *reply = mgr->post(QNetworkRequest(QUrl(XXXXXX)), multiPart);
multiPart->setParent(reply); // delete the multiPart with the reply
// lock
lockSend = true;
}
void DirectoryWatcher::saveResponse(QNetworkReply *rep) {
// get the response
QByteArray bts = rep->readAll();
QString str(bts);
// compute new path
QString partName = currentFileSent.mid(1, currentFileSent.length());
QString newPath = QString("%1/A%2.xml").arg(directoryLastChanged, partName);
qDebug() << "new path: " << newPath << endl;
switch (rep->error()) {
case QNetworkReply::NoError: {
qDebug() << "NO ERROR" << endl;
// save response to a file.
QFile file(newPath);
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << str;
file.close();
break;
}
default:
// case QNetworkReply::TimeoutError :
// case QNetworkReply::HostNotFoundError :
qDebug() << "NETWORK REPLY ERROR" << endl;
// resend the file if the counter is < 10
if (this->resendCounter < 5) {
// delay by n sec
QTime dieTime = QTime::currentTime().addSecs(1);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
sendFileAndAccept(this->lastPathSent.toStdString().c_str());
} else {
// after 10 attempts, we're probably sure that the network is down
// save the file somewhere and generate a default one to prevent timeouts.
qDebug() << "Saving file for later..." << endl;
if (!saveFileForLater(lastPathSent.toStdString().c_str())) {
qDebug() << "ERROR SAVING FILE, CHECK IF FOLDER EXISTS AND THE PERMISSIONS." << endl;
}
// generate a default one to prevent timeouts.
qDebug() << "Generate a default file..." << endl;
// ...
}
break;
}
// unlock
lockSend = false;
rep->deleteLater(); // prevent memory leak
}
bool DirectoryWatcher::saveFileForLater(const char* pathToRequestFile) {
QFile file(pathToRequestFile);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
qDebug() << "readonly and text" << endl;
return false;
}
QString path(pathToRequestFile);
QFileInfo fileinfo(path);
QString newPath = "C:\\data\\offline\\" + fileinfo.fileName();
return file.copy(newPath);
}
感谢您的帮助。
答案 0 :(得分:2)
directoryChanged的2次发出的最可能原因是保存更改时的普通编辑器会删除并将新版本的文件写入磁盘。这就是为什么在删除文件时有一个信号,以及在重新创建文件时有一个信号的原因。