QT断点续传

 

//功能:    根据一个URL地址将数据保存到指定路径下,支持断点续传
//参数:    url            --需要访问的URL地址
//         SavePath       --需要保存的路径
//DownedSize 已经下载的大小
// totalSize 文件总大小
//返回值:  ture --成功 false --失败
bool HttpGet::DownFile(const QUrl &url,const QString &SavePath,int DownedSize,int totalSize)
{ //创建父文件夹
  QString curPath=QApplication::applicationDirPath()+"/Files";
  if(!QDir(curPath).exists())
  {
   QDir photoDir;
   photoDir.mkdir(curPath);
  }
 //创建子文件夹
    if(!QDir(SavePath).exists())
    {
     QDir photoDir;
     photoDir.mkdir(SavePath);
    }
    QNetworkRequest qheader;
    qheader.setUrl(url);
    QString Range="bytes "+QString::number(DownedSize)+"-";//告诉服务器从DownedSize起开始传输
    qheader.setRawHeader("Range",Range.toAscii());

        QNetworkAccessManager manager;
        //参考 http://www.qtforum.org/article/31355/qnetworkaccessmanager-using-custom-headers-to-download-a-file.html
        QEventLoop loop;
        //QNetworkReply *reply = manager.get(QNetworkRequest(url));
        QNetworkReply *reply = manager.get(QNetworkRequest(qheader));
        QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
        loop.exec();
        QFileInfo fileInfo=url.path();
        QFile file(SavePath+fileInfo.fileName());
        file.open(QIODevice::WriteOnly);
        file.write(reply->readAll());
        delete reply;
        return true;
}

使用

  getter.DownFile(QUrl(FileUrl),QString(CurrentPath),0,FileSize);
  QObject::connect(&getter, SIGNAL(finished()),  SLOT(quit()));

断点续传原理:需要在HTTP请求的header中添加Rang节,告诉服务器从文件的那个位置开始传输.格式为bytes 开始传输的位置-

你可能感兴趣的:(manager,服务器,url,qt,getter,Signal)