1
我使用Get方法從Url下載「.apk」文件。 該文件已成功從服務器上下載到我的磁盤上。 我實際上想要將一個進度條添加到我的程序中。問題是:我可以顯示bytesReceived,但無法顯示我正在下載的文件(ContentLenth)的總字節數。我怎樣才能從服務器取得它。Qt5 - 從Url下載文件時獲取內容的長度
這裏是我得到我的qDebug同時下載:
3498 of -1
799062 of -1
1923737 of -1
3037550 of -1
3200231 of 3200231
這裏是我的代碼:
void DownloadApk::LaunchDownload()
{
QNetworkProxy proxy;
proxy.setType(QNetworkProxy::HttpProxy);
proxy.setHostName("proxy");
proxy.setPort(8080);
QNetworkProxy::setApplicationProxy(proxy);
QUrl url("I put my Url here");
QNetworkRequest request(url);
_file = new QFile("C:/Users/Desktop/testdownload/downloadedFile.apk");
_file->open(QIODevice::WriteOnly);
QNetworkAccessManager *_manager= new QNetworkAccessManager;
_reply = _manager->get(request);// Manager is my QNetworkAccessManager
_file->write(_reply->readAll());
connect(_reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(error(QNetworkReply::NetworkError)));
connect(_reply, SIGNAL(downloadProgress(qint64, qint64)),
this, SLOT(updateProgress(qint64, qint64)));
connect(_reply, SIGNAL(finished()),
this, SLOT(finished()));
}
void DownloadApk::error(QNetworkReply::NetworkError err)
{qDebug() << err;
// Manage error here.
_reply->deleteLater();
}
void DownloadApk::updateProgress(qint64 read, qint64 total)
{
qDebug() << read <<"of"<<total ;
QByteArray b = _reply->readAll();
QDataStream out(_file);
out << b;
}
void DownloadApk::finished()
{
QMessageBox::information(this, tr("Complete"), tr("Successfully Downloaded"));
// Done
_reply->deleteLater();
_file->close();
// probably delete the file object too
}
服務器是否向您提供內容長度?你有一個wireshark跟蹤來支持它嗎? –
你說得對!我教過contentLength是在http頭上自動發送的。顯然我錯了。我糾正了我的API。這個Qt代碼正常工作。感謝您的時間@Kuba Ober – Chakib