Lucas Lucas - 1 month ago 8
C++ Question

File download - check for error before file write

I'm using Qt to download a file from HTTP, for that, I'm using two signals:

connect(currentDownload, SIGNAL(finished()),
SLOT(downloadFinished()));
connect(currentDownload, SIGNAL(readyRead()),
SLOT(downloadReadyRead()));


Callbacks:

void DownloadManager::downloadFinished()
{
output.close();

if (currentDownload->error()) {
// download failed
std::cout << "Failed: [" << currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()
<< "] " << qPrintable(currentDownload->errorString()) << std::endl;
} else {
std::cout << "Download succeeded" << std::endl;
}

currentDownload->deleteLater();
startNextDownload();
}

void DownloadManager::downloadReadyRead()
{
output.write(currentDownload->readAll());
}


The problem I'm having is that I cant figure out how to skip writing the output file, if any error has occured during download for whatever reason. This is not logical - since I can only check for error during the
finished()
signal emitting. Checking for errors during the
readyRead()
signal won't show any, even though they exist. In the results, 404 output file will be written to the disk. How can I solve that?

Answer

You should use QNetworkRequest to get all the infromation. Refer to this example.

QNetworkAccessManager provide more signals to tackle errors.

QNetworkReply *reply = manager->get(request);
connect(reply, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
        this, SLOT(slotError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)),
        this, SLOT(slotSslErrors(QList<QSslError>)));
Comments