我目前在 Qt 线程上遇到问题。
我必须在 QThread 中上传文件列表,但显然一个上传不起作用和/或我的插槽从未被调用。如果我把这些方法放在线程之外,它就可以完美地工作。
这是 run() 方法:
void UploadThread::run()
{
for (int i = 0; i < Window::_listUpload.size(); i++) {
qDebug() << Window::_listUpload[i].getPath();
this->sendFile(Window::_listUpload[i].getPath());
}
}
这是 sendFile() 方法:
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*)));
}
这是我的插槽:
void UploadThread::uploadFinished(QNetworkReply *reply)
{
_isFinished = true;
}
void UploadThread::receiveUploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
qDebug() << bytesSent << " " << bytesTotal;
}
您在我的代码中看到问题了吗?谢谢你。