3

In the example below sometimes the file is downloaded correctly, and sometimes, I'm getting these values in the qDebug() added into the downloadProgress lambda:

Percent complete:  -1.08905e+09
Downloaded  11623330  of  -1

And then the download fails, I mean it saves a zip file with 0 bytes.

        QNetworkAccessManager *manager = new QNetworkAccessManager(this);

        QNetworkRequest request;
        // Random link just to test:
        request.setUrl(
            QUrl("https://github.com/FFmpeg/FFmpeg/archive/refs/tags/n5.0.2.zip"));

        QNetworkReply *reply = manager->get(request);

        connect(reply, &QNetworkReply::downloadProgress,
            [this, reply](qint64 bytesReceived, qint64 bytesTotal)
        {
            qDebug() << "Downloaded " << bytesReceived << " of " << bytesTotal;
            double percentComplete = (bytesReceived * 100.0) / bytesTotal;
            qDebug() << "Percent complete: " << percentComplete;
        });

        connect(reply, &QNetworkReply::finished, [this, reply]() 
        {
            if (reply->error() != QNetworkReply::NoError)
            {
                qDebug() << "Error: " << reply->errorString();
            } else 
            {
                QString fileName = "C:/Users/Raja/Downloads/file.zip";
                QFile file(fileName);
                if (file.open(QIODevice::WriteOnly)) 
                {
                    file.write(reply->readAll());
                    file.close();
                    qDebug() << "File downloaded successfully";
                } else
                    qDebug() << "Error: Unable to open the file";
            }
            reply->deleteLater();
        });

What i'm missing?

Cesar
  • 41
  • 2
  • 5
  • 16

1 Answers1

1

Did you read the documentation?

It says that bytesTotal is -1 if the total size is unknown and

The download is finished when bytesReceived is equal to bytesTotal. At that time, bytesTotal will not be -1.

In other words: That behavior is expected and just means the download is still in progress. This probably happens when the server doesn't send a content-length header. See What's the "Content-Length" field in HTTP header?

Homer512
  • 9,144
  • 2
  • 8
  • 25