/功能: 根据一个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;
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 开始传输的位置-