Qt断点续传基本思想从上次暂停文件暂停的位置开始新的下载,比如一个文件共500k,已下载了100k,则重新开始的时候从文件的末尾开始写数据,设置文件指针的偏移量,seek()。然后就是从http服务器上下载数据也从文件的100k处开始下载。明白了这个就好操作了。
设置一个参数qint64 datasize,用于在下载暂停的时候保存当前文件的大小,datasize = file.size();
重新开始时file.seek(datasize);
然后就可以接着上次位置写数据。
设置从http服务器100k出开始下载,
QNetworkRequest qheader;
qheader.setRawHeader("Range",tr("bytes=%1-").arg(downsize).toUtf8());
reply = m_netwManager->get(QNetworkRequest(qheader));
connect(reply,SIGNAL(finished()),this,SLOT(FinishLoad()));
connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(UpdateBar(qint64,qint64)));
connect(reply,SIGNAL(readyRead()),this,SLOT(ReadyFile()));
其中downloadProgress(qint64 data,qint64 totalsize)//下载数据的大小,从开始到结尾处的总大小,这里就返回400k
QNetworkReply 暂停下载调用abort(),在暂停后最后会发出finished信号。
这应该就完成了断点续传的功能。
开始下载的函数
void Text::updateProgram()
{
//QFile file("123");
if(netfile != NULL)
{
if(!netfile->open(QIODevice::WriteOnly))
{
return;
}
netfile->seek(downsize);
qDebug()<<"file exit "<}
else{
netfile = new QFile("123");if(!netfile->open(QIODevice::WriteOnly)){
return;}
qDebug()<<"file not exit "<}
bar->show();
httpRequestAborted = false;update_status == Text::stop;QUrl u("http://192.168.1.101/123.zip");qDebug()<<"downsize"< QNetworkRequest qheader;qheader.setUrl(u);
qheader.setRawHeader("Range",tr("bytes=%1-").arg(downsize).toUtf8());reply = m_netwManager->get(QNetworkRequest(qheader));connect(reply,SIGNAL(finished()),this,SLOT(FinishLoad()));connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(UpdateBar(qint64,qint64)));connect(reply,SIGNAL(readyRead()),this,SLOT(ReadyFile()));updatebtn->disconnect();
connect(updatebtn,SIGNAL(clicked()),this,SLOT(cancelDownload()));}
写过程
void Text::ReadyFile(){if (netfile)netfile->write(reply->readAll());
}
void Text::FinishLoad(){qDebug()<<"finished";if (httpRequestAborted) {//httpRequestAborted暂停的标志if (netfile) {netfile->close();
}
reply->deleteLater();
return;}
netfile->close();
bar->hide();
reply->deleteLater();
}
更新进度条
void Text::UpdateBar(qint64 x,qint64 size){qDebug()<<"x"<"size"< bar->setMaximum(size);
bar->setValue(datasize+x);
}
参考:http://hi.baidu.com/cmdmac/item/28af7f0c0083e3f1a01034a4(http协议)
Qt 4.7 demo networking http client