1
我有使用webkit的這個QT腳本。我可以下載文件沒有問題,但我無法在文件對話框中移動進度條。我認爲在我打電話給進度對話框之前已經發送了網絡回覆,因爲點擊下載鏈接有延遲,然後被回送到控制檯。如何在完成之前攔截網絡回覆並調用unsupportedContent()方法?文件下載問題
編輯: 我可以剝離出來,並使用reply = manager.get(QNetworkRequest(url));
,但我真的不知道這可能是URL鏈接的任何用戶點擊,沒有預定義的URL?
void MainWindow::unsupportedContent(QNetworkReply *reply) {
qDebug() << "Left click - download!";
qDebug() << "Bytes to download: " << reply->bytesAvailable();
QString str = reply->rawHeader("Content-Disposition");
QString end = str.mid(21);
end.chop(1);
qDebug() << "File name: " << end;
qDebug() << "File type: " << reply->rawHeader("Content-Type");
qDebug() << "File size (bytes): " << reply->bytesAvailable();
QString defaultFileName = QFileInfo(end).fileName();
QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), defaultFileName);
if (fileName.isEmpty()) return;
file = new QFile(fileName);
if(!file->open(QIODevice::WriteOnly))
{
QMessageBox::information(this, "Downloader",
tr("Unable to save the file %1: %2.")
.arg(fileName).arg(file->errorString()));
delete file;
file = NULL;
return;
}
downloadRequestAborted = false;
connect(reply, SIGNAL(finished()), this, SLOT(downloadFinished()));
connect(reply, SIGNAL(readyRead()), this, SLOT(downloadReadyRead()));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
progressDialog->setLabelText(tr("Downloading %1...").arg(fileName));
//downloadButton->setEnabled(false);
progressDialog->exec();
//QFile file(fileName);
//file.open(QIODevice::WriteOnly);
//file.write(reply->read(reply->bytesAvailable()));
//file.close();
}
void MainWindow::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
qDebug() << bytesReceived << bytesTotal;
if(downloadRequestAborted)
return;
progressDialog->setMaximum(bytesTotal);
progressDialog->setValue(bytesReceived);
}
void MainWindow::downloadReadyRead()
{
if(file)
file->write(reply->read(reply->bytesAvailable()));
}
void MainWindow::downloadFinished()
{
qDebug() << "Download finished!";
if(downloadRequestAborted)
{
if(file)
{
file->close();
file->remove();
delete file;
file = NULL;
}
reply->deleteLater();
progressDialog->hide();
//downloadButton->setEnabled(true);
return;
}
downloadReadyRead();
progressDialog->hide();
//downloadButton->setEnabled(true);
file->flush();
file->close();
if(reply->error())
{
//Download failed
QMessageBox::information(this, "Download failed", tr("Failed: %1").arg(reply->errorString()));
}
reply->deleteLater();
reply = NULL;
delete file;
file = NULL;
}
void MainWindow::cancelDownload()
{
downloadRequestAborted = true;
reply->abort();
progressDialog->hide();
//downloadButton->setEnabled(true);
}
不幸的是,它可能試圖訪問一個頭,或獲取信息bytesAvailable,造成回覆要全部下載的......我建議你嘗試剝離一切,這是沒有必要顯示進度和看看它是否改變了行爲。附:由於緩衝,控制檯輸出可能會有些棘手,但這並不意味着太多。 –
謝謝@JohnChadwick我會盡快嘗試。儘管答覆已經在我的unsupportedContent()方法中完成。我可以去掉它並使用'reply = manager.get(QNetworkRequest(url));'但我實際上並不知道URL可能是用戶點擊的任何鏈接,沒有預定義的URL? – Kal