qt通過http請求下載檔案(支援斷點續傳)
阿新 • • 發佈:2021-06-27
點選檢視程式碼
void Download::on_downloadBtn_clicked() { if(file.exists()) { if(isDownload==false) { ui->downloadBtn->setText("暫停"); isDownload=true; if(isDisconnect) { startDownload(ui->urlEdit->document()->toPlainText()); } } else { ui->downloadBtn->setText("下載"); isDownload=false; isDisconnect=true; disconnect(reply,0,0,0);//斷開與reply相關的所有連線 reply->abort(); reply->deleteLater(); reply=NULL; } } if(file.exists()&&!isDownLoadError) { return; } QString url=ui->urlEdit->document()->toPlainText(); int index=url.lastIndexOf('/'); QString filename=url.mid(index+1); QString filePath=QFileDialog::getExistingDirectory(NULL,"儲存路徑","./"); file.setFileName(filePath+'/'+filename); if(!file.open(QIODevice::ReadWrite|QIODevice::Append)) { receivedBytes=file.size(); QMessageBox::information(NULL,"info","open file fail"); return; } { ui->downloadBtn->setText("暫停"); isDownload=true; isDownLoadError=false; } startDownload(url); } void Download::startDownload(QString url) { QNetworkRequest request; request.setUrl(QUrl(url)); //支援斷點續傳 QString strRange = QString("bytes=%1-").arg(receivedBytes); request.setRawHeader("Range", strRange.toUtf8()); reply=manager->get(request); connect(reply,&QNetworkReply::readyRead,this,&Download::dealData); connect(reply,&QNetworkReply::finished,[this]() { reply->deleteLater(); if(!isDownLoadError) { ui->processImg->setPixmap(QPixmap(":/resources/progress/finished.png")); ui->downloadBtn->setEnabled(false); ui->downloadBtn->setText("完成"); } file.close(); } ); connect(reply,&QNetworkReply::downloadProgress,this,&Download::downloadProcess); connect(reply,QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error),this,&Download::downloadError); } void Download::dealData() { QNetworkReply*reply=dynamic_cast<QNetworkReply*>(sender()); file.write(reply->readAll()); receivedBytes=file.size(); } void Download::downloadProcess(qint64 received, qint64 total) { if(firstDownload) { /* * 把第一次下載時的檔案長度(即整個檔案的大小)儲存起來 * 因為斷點續傳total會越來越小 */ fileSize=QString::number(total); firstDownload=false; } /* * 之所以不用函式提供的兩個引數(received、total), * 是因為搞了半天那個進度條顯示不正確,故採用此法 * 如果你有更好的辦法,部落格留言。。。 */ ui->progressBar->setValue(receivedBytes); ui->progressBar->setMaximum(fileSize.toInt()); }
演示效果:
參考連結:
http://www.suoniao.com/topic/5f3d7b8470fe9927be5bf408
https://blog.csdn.net/GoForwardToStep/article/details/52704464
https://blog.csdn.net/u013015629/article/details/111240513
https://blog.csdn.net/JimBraddock/article/details/84170461
原始碼連結:
連結:https://pan.baidu.com/s/1fefKwWqSCmJsa5e6jioZsA
提取碼:wscq
(程式碼如有問題,求指正。。。)