添加头文件:
cpp
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QDesktopServices>
创建对象:
cpp
QNetworkAccessManager networkManager;//网络管理
QNetworkReply *reply; //网络响应
QFile *downloadedFile;//下载保存的临时文件
输入url地址:
cpp
QUrl newUrl = QUrl::fromUserInput(urlSpec);//URL地址
创建临时文件:
cpp
downloadedFile =new QFile(fullFileName);
if (!downloadedFile->open(QIODevice::WriteOnly))
{
QMessageBox::information(this, tr("错误"),"临时文件打开错误");
发送请求,创建网络响应:
cpp
reply = networkManager.get(QNetworkRequest(newUrl));
连接信号与槽:
cpp
connect(reply, SIGNAL(finished()), this, SLOT(on_finished()));
connect(reply, SIGNAL(readyRead()), this, SLOT(on_readyRead()));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
this, SLOT(on_downloadProgress(qint64,qint64)));
void MainWindow::on_finished()
{//网络响应结束
QFileInfo fileInfo;
fileInfo.setFile(downloadedFile->fileName());
downloadedFile->close();
delete downloadedFile;
downloadedFile = Q_NULLPTR;
reply->deleteLater(); //
reply = Q_NULLPTR;
if (ui->checkOpen->isChecked())//打开下载的文件
QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absoluteFilePath()));
ui->btnDownload->setEnabled(true);
}
void MainWindow::on_readyRead()
{//读取下载的数据
downloadedFile->write(reply->readAll());
}
void MainWindow::on_downloadProgress(qint64 bytesRead, qint64 totalBytes)
{//下载进程
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(bytesRead);
}