关于qt的http上传和下载资源的进度条显示

qt提供的一系列接口是的qt程序在网络通信方面非常便捷,在项目开发中很多朋友会用到http协议来上传文件到服务器或者从服务器下载文件下来,这里面上传和下载的进度显示是一个提高用户体验很重要的实现,在这里简要讲一下这两个实现:

其实实现很简单,只要连接QNetworkReply类的两个信号便可以,先看文档:

上传:

void QNetworkReply::uploadProgress(qint64 bytesSent, qint64 bytesTotal)
This signal is emitted to indicate the progress of the upload part of this network request, if there's any. If there's no upload associated with this request, this signal will not be emitted.
The bytesSent parameter indicates the number of bytes uploaded, while bytesTotal indicates the total number of bytes to be uploaded. If the number of bytes to be uploaded could not be determined, bytesTotal will be -1.
The upload is finished when bytesSent is equal to bytesTotal. At that time, bytesTotal will not be -1.

下载:

void QNetworkReply::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
This signal is emitted to indicate the progress of the download part of this network request, if there's any. If there's no download associated with this request, this signal will be emitted once with 0 as the value of both bytesReceived and bytesTotal.
The bytesReceived parameter indicates the number of bytes received, while bytesTotal indicates the total number of bytes expected to be downloaded. If the number of bytes to be downloaded is not known, bytesTotal will be -1.
The download is finished when bytesReceived is equal to bytesTotal. At that time, bytesTotal will not be -1.
Note that the values of both bytesReceived and bytesTotal may be different from size(), the total number of bytes obtained through read() or readAll(), or the value of the header(ContentLengthHeader). The reason for that is that there may be protocol overhead or the data may be compressed during the download.

只要connect这两个信号到相应的槽,获得两个参数,便可以知道当前进度。其中第二个参数是当前操作文件的大小,第一个便是已上传或下载的大小

如何使用这两个信号?

大家都知道用qt的QNetworkAccessManager可以上传和下载,在调用get()和post()的时候放回一个QNetworkReply指针,我要做的就是connect这个指针的这两个信号就可以获得状态了:

QNetworkReply *reply;
QNetworkAccessManager *manager = new QNetworkAccessManager;
......

reply = manager->get(QNetworkRequest(url));
//更新进度条
connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(updateDataReadProgress(qint64,qint64)));

有必要可以联系我要例子~

发布了4 篇原创文章 · 获赞 0 · 访问量 9474

猜你喜欢

转载自blog.csdn.net/yangkping123/article/details/46804181