在QObject中无效的分段上传已移至线程

时间:2016-01-28 23:08:44

标签: c++ multithreading qt

我正在尝试使用Qt中的MultiPart将图像上传到我的网络服务器。当我通过按钮从我的MainWindow运行下面的代码时,它工作正常。

当我尝试在继承自移动到线程的QObject的类中实现确切代码时,它没有达到te SIGNAL / SLOT并且没有上传文件。

有人可以指出我的错误在哪里吗?对此有一段时间没有任何积极的结果。

谢谢!

线程/工人类的实现

#include "screenshotworker.h"
#include "session.h"
#include "json.h"
#include "mainwindow.h"

#include <QtNetwork>
#include <QByteArray>
#include <QMessageBox>
#include <QDesktopWidget>
#include <QApplication>


ScreenshotWorker::ScreenshotWorker(QObject *parent) : QObject(parent)
{

}

void ScreenshotWorker::DoSetup(QThread *cThread, Session *aSession)
{
   session = aSession;
   connect(cThread, SIGNAL(started()), this, SLOT(DoWork()));
}

void ScreenshotWorker::DoWork()
{

    while(session->sessActive)
    {

        QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

        QHttpPart textPart;
        textPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"session\""));
        textPart.setBody(QByteArray::number(session->session_id));

        QHttpPart imagePart;
        imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
        imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"userfile\"; filename=\"screen.png\""));
        QFile *file = new QFile("screen.png");
        file->open(QIODevice::ReadOnly);
        imagePart.setBodyDevice(file);
        file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart

        multiPart->append(textPart);
        multiPart->append(imagePart);

        QUrl url("http://........");
        QNetworkRequest request(url);

        QNetworkAccessManager *manager = new QNetworkAccessManager();
        reply = manager->post(request, multiPart);
        multiPart->setParent(reply); // delete the multiPart with the reply


        connect(reply, SIGNAL( uploadProgress(qint64, qint64) ), this, SLOT( uploadProgress(qint64,qint64) ) ) ;
        connect(reply, SIGNAL(finished()), this, SLOT(uploadDone()));

        sleep(10);
     }
}

void ScreenshotWorker::uploadProgress(qint64 bytesSent, qint64 bytesTotal) {
    qDebug() << "Uploaded" << bytesSent << "of" << bytesTotal;
}

void ScreenshotWorker::uploadDone() {
    qDebug() << "Finished" << reply->errorString() <<reply->attribute( QNetworkRequest::HttpStatusCodeAttribute).toInt();
    qDebug()<<reply->readAll();

    reply->deleteLater();
}

按下按钮,启动线程。

QThread *cThread2 = new QThread();
ScreenshotWorker *cWorker2 = new ScreenshotWorker();

cWorker2->DoSetup(cThread2, mSession);
cWorker2->moveToThread(cThread2);
cThread2->start();

1 个答案:

答案 0 :(得分:0)

感谢上面的评论,我能够通过添加事件循环来解决这个问题。

QEventLoop loop;        
connect(reply, SIGNAL(finished()),&loop, SLOT(quit()));
loop.exec();