httpdownload.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #include "httpdownload.h"
  2. HttpDownload::HttpDownload(QObject *parent) :
  3. QObject(parent)
  4. {
  5. this->retCode = 0;
  6. this->reply = 0;
  7. }
  8. HttpDownload::~HttpDownload()
  9. {
  10. if (reply) {
  11. delete reply;
  12. }
  13. // qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")\
  14. // <<"HttpDownload Destroyed.";
  15. }
  16. int HttpDownload::downloadFile(QString fileUrl,QString savePath)
  17. {
  18. url = fileUrl;
  19. QFileInfo fileInfo(url.path());
  20. QString fileName ;
  21. if(savePath.endsWith('/'))
  22. fileName = savePath+fileInfo.fileName();
  23. else
  24. fileName = savePath + "/" + fileInfo.fileName();
  25. if (QFile::exists(fileName))
  26. {
  27. QFile::remove(fileName);
  28. }
  29. file = new QFile(fileName);
  30. QString str = "²»Äܱ£´æÎļþ %1: %2.";
  31. if (!file->open(QIODevice::WriteOnly)) {
  32. qDebug()<< str.arg(fileName).arg(file->errorString());
  33. delete file;
  34. file = 0;
  35. return -1;
  36. }
  37. finish = false;
  38. httpRequestAborted = false;
  39. startRequest(url);
  40. while(!finish)
  41. QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
  42. return retCode;
  43. }
  44. void HttpDownload::startRequest(QUrl url)
  45. {
  46. reply = qnam.get(QNetworkRequest(url));
  47. connect(reply, SIGNAL(finished()),
  48. this, SLOT(httpFinished()));
  49. connect(reply, SIGNAL(readyRead()),
  50. this, SLOT(httpReadyRead()));
  51. connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
  52. this, SLOT(updateDataReadProgress(qint64,qint64)));
  53. }
  54. void HttpDownload::httpFinished()
  55. {
  56. if (httpRequestAborted) {
  57. if (file) {
  58. file->close();
  59. file->remove();
  60. delete file;
  61. file = 0;
  62. }
  63. reply->deleteLater();
  64. retCode = -1;
  65. finish = true;
  66. return;
  67. }
  68. file->flush();
  69. file->close();
  70. finish = true;
  71. }
  72. void HttpDownload::httpReadyRead()
  73. {
  74. if (file)
  75. file->write(reply->readAll());
  76. }
  77. void HttpDownload::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
  78. {
  79. if (httpRequestAborted)
  80. return;
  81. }