.pro文件添加
QT += network
.ui界面
界面头文件代码:
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QFile>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
protected slots:
// 读取数据
void slot_readyRead();
// 传输完毕
void slot_finished();
// 数据尺寸
void slot_downloadProcess(qint64 bytesReceived, qint64 bytesTotal);
private slots:
// 点击下载
void on_btnDownload_clicked();
private:
Ui::Widget *ui;
QNetworkAccessManager* m_pManager = {NULL};
QNetworkReply *m_pReplay = {NULL};
QFile* m_pFile = {NULL};
QUrl m_url;
};
界面cpp代码:
Widget::Widget(QWidget *parent)
: QWidget(parent)
, ui(new Ui::Widget)
{
ui->setupUi(this);
// 初始化网络管理
if(!m_pManager)
{
m_pManager = new QNetworkAccessManager(this);
}
}
Widget::~Widget()
{
delete ui;
}
void Widget::slot_readyRead()
{
if(m_pReplay->error() == QNetworkReply::NoError && m_pReplay->bytesAvailable())
{
QFile file(m_url.fileName());
if(file.open(QIODevice::WriteOnly/* | QIODevice::Text */| QIODevice::Append))
{
file.write(m_pReplay->readAll());
file.flush();
file.close();
}
}
}
void Widget::slot_finished()
{
ui->edtLog->append(m_pReplay->errorString());
ui->edtLog->append(u8"下载完毕");
}
void Widget::slot_downloadProcess(qint64 bytesReceived, qint64 bytesTotal)
{
ui->pbDown->setRange(0,bytesTotal);
ui->pbDown->setValue(bytesReceived);
}
void Widget::on_btnDownload_clicked()
{
// 获取下载连接
QString str = ui->edtUrl->text();
// 生成URL地址
m_url = QUrl(str);
if(m_url.isValid() == false)
{
ui->edtLog->append(u8"地址不可用");
return;
}
// 创建请求
QNetworkRequest request(m_url);
// 回复
if(!m_pReplay)
{
m_pReplay = m_pManager->get(request);
ui->edtLog->append(m_pReplay->errorString());
connect(m_pReplay, SIGNAL(readyRead()),this,SLOT(slot_readyRead()));
connect(m_pReplay,SIGNAL(finished()),this,SLOT(slot_finished()));
connect(m_pReplay,SIGNAL(downloadProgress(qint64 , qint64 )),this,SLOT(slot_downloadProcess(qint64,qint64)));
}
ui->edtLog->append(u8"开始下载");
}
备注:
(1)存储本地的文件句柄可以一开始创建,不能每次都打开写入,提升效率;
(2)QFile的打开属性不能写QIODevice:Text!!!
(3)如果是大文件传输的话,获取到数据后,可以开启缓冲队列,在子线程进行数据读取写入工作;
(6)SSL模块可能需要自己重新编译一下,否则会初始化失败;