#include "Widget2.h"
#include "ui_Widget2.h"
#include <QFileInfo>
#include <QDebug>
Widget2::Widget2(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget2)
{
ui->setupUi(this);
manager = new QNetworkAccessManager(this);
file = 0;
}
Widget2::~Widget2()
{
delete ui;
}
void Widget2::startRequest(QUrl url)
{
reply = manager->get(QNetworkRequest(url));
connect(reply, SIGNAL(readyRead()), this, SLOT(httpReadyRead()));
connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDataReadProgress(qint64,qint64)));
connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));
}
void Widget2::on_downloadButton_clicked()
{
url = ui->lineEdit->text();
qDebug() << "url: " << url;
QFileInfo url_path(url.path());
qDebug() << "url_path: " << url_path.absoluteFilePath();
QString fileName(url_path.fileName());
qDebug() << "fileName: " << fileName;
if( fileName.isEmpty() ) fileName = "index.html";
if( !file ) file = new QFile(fileName);
if( !file->open(QIODevice::WriteOnly))
{
qDebug() << "file open error";
delete file;
file = 0;
return;
}
startRequest(url);
}
void Widget2::httpReadyRead()
{
if( file ) file->write(reply->readAll());
}
void Widget2::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
{
ui->progressBar->setMaximum(totalBytes);
ui->progressBar->setValue(bytesRead);
}
void Widget2::httpFinished()
{
file->flush();
file->close();
delete file;
file = 0;
reply->deleteLater();
reply = 0;
}
QNetworkAccessManager
最新推荐文章于 2024-09-06 23:48:31 发布