Jared Price
Jared Price

Reputation: 5375

Qt getting network requests with QNetworkReply that download data to temp file

I am having some issues reading an online file. I'm trying to read what is in the file after it gets downloaded to a temporary file. Here is my code:

void MainWindow::fileIsReady( QNetworkReply * reply)
{
    QTemporaryFile tmpFile;
    tmpFile.write(reply->readAll());

    QByteArray asdf = reply->readAll();
    qDebug() (QString("%1").arg(asdf.length())); // returns 0

    if (tmpFile.open())
    {
        qDebug << "attempting to read file";

        QTextStream stream(&tmpFile);
        QString value = stream.readAll();
        qDebug << value; // value is returning nothing
    }
    else
    {
        qDebug() << "failed to open internet file";
    }
}

// in MainWindow constructor (MainWindow::MainWindow)...


QNetworkAccessManager * manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileIsReady(QNetworkReply*)) );
manager->get(QNetworkRequest(QUrl("https://www.website.com/stuff/file.exe.md5")));

I'm going to be using this to compare two md5 strings.

Upvotes: 0

Views: 2538

Answers (2)

Jared Price
Jared Price

Reputation: 5375

So turns out I was dumb and forgot to open the reply first. Also, it was unnecessary for me to create a temp file. Here is my solution::

void MainWindow::fileIsReady( QNetworkReply * reply)
{
    if (reply->error() == QNetworkReply::NoError)
    {
        if (reply->open(QIODevice::ReadOnly))
        {
            QByteArray asdf = reply->readAll();

            qDebug() << (QString("asdf %1").arg(asdf.length()));

            qDebug() << (QString(asdf));
        }
        else
        {
            qDebug << "cant open reply";
        }
    }
}

Upvotes: 0

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

There are several issues in your code:

  1. You need to open tmpFile before writing to it.
  2. reply->readAll() will return data only once. Further calls will return empty array. Once you received data using readAll, it's your responsibility to store it in a variable if you need it later.
  3. After you wrote someting to file, the file pointer is at its end. You cannot read anything from it because there is no data there. You can use seek to move pointer to the beginning of the file and read its content.
  4. There is no point in reading from file just after you wrote data to it. You can use QTextStream on QNetworkReply directly to read text from it. (Maybe this was just for debugging, I don't know.)
  5. It's hard to believe that you need to create a temporary file just to calculate md5. There are simplier ways to do that.

Upvotes: 1

Related Questions