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