I am currently experiencing issues on a Qt thread.
I have to upload a list of files in a QThread, but apparently one upload doesn’t work and/or my slots are never called. If I put the methods out of the thread it works perfectly.
Here is the run() method :
void UploadThread::run()
{
for (int i = 0; i < Window::_listUpload.size(); i++) {
qDebug() << Window::_listUpload[i].getPath();
this->sendFile(Window::_listUpload[i].getPath());
}
}
Here is the sendFile() method :
void UploadThread::sendFile(const QString & path)
{
QFreeDesktopMime mime;
QNetworkAccessManager *manager = new QNetworkAccessManager;
QFileInfo fInfo(path);
QNetworkRequest request(QUrl("http://my-url/"));
QNetworkReply *reply;
QString bound = "---------------------------723690991551375881941828858";
QByteArray data(QString("--"+bound+"\r\n").toAscii());
data += "Content-Disposition: form-data; name=\"action\"\r\n\r\n";
data += "\r\n";
data += QString("--" + bound + "\r\n").toAscii();
data += "Content-Disposition: form-data; name=\"file\"; filename=\""+fInfo.fileName()+"\"\r\n";
data += "Content-Type: "+mime.fromFile(path)+"\r\n\r\n";
QFile file(fInfo.absoluteFilePath());
file.open(QIODevice::ReadOnly);
data += file.readAll();
data += "\r\n";
data += QString("--" + bound + "\r\n").toAscii();
data += QString("--" + bound + "\r\n").toAscii();
data += "Content-Disposition: form-data; name=\"desc\"\r\n\r\n";
data += "Description for my image here :)\r\n";
data += "\r\n";
request.setRawHeader(QString("Accept-Encoding").toAscii(), QString("gzip,deflate").toAscii());
request.setRawHeader(QString("Content-Type").toAscii(),QString("multipart/form-data; boundary=" + bound).toAscii());
request.setRawHeader(QString("Content-Length").toAscii(), QString::number(data.length()).toAscii());
reply = manager->post(request, data);
QObject::connect(reply, SIGNAL(uploadProgress(qint64,qint64)), currentThread(), SLOT(receiveUploadProgress(qint64, qint64)));
QObject::connect(manager, SIGNAL(finished(QNetworkReply*)), currentThread(), SLOT(uploadFinished(QNetworkReply*)));
}
And here are my slots :
void UploadThread::uploadFinished(QNetworkReply *reply)
{
_isFinished = true;
}
void UploadThread::receiveUploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
qDebug() << bytesSent << " " << bytesTotal;
}
Do you see a problem in my code ?
Thank you.
Ok, I get it.
For each upload, I need to start the QEventLoop using exec(), and at the end of an upload I have to use exit() in order to finish the QEventLoop. It now works like a charm.