//功能: 根據一個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 開始傳輸的位置
http://blog.csdn.net/henreash/article/details/7267271
