| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- #include "httpdownload.h"
- HttpDownload::HttpDownload(QObject *parent) :
- QObject(parent)
- {
- this->retCode = 0;
- this->reply = 0;
- }
- HttpDownload::~HttpDownload()
- {
- if (reply) {
- delete reply;
- }
- // qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss")\
- // <<"HttpDownload Destroyed.";
- }
- int HttpDownload::downloadFile(QString fileUrl,QString savePath)
- {
- url = fileUrl;
- QFileInfo fileInfo(url.path());
- QString fileName ;
- if(savePath.endsWith('/'))
- fileName = savePath+fileInfo.fileName();
- else
- fileName = savePath + "/" + fileInfo.fileName();
- if (QFile::exists(fileName))
- {
- QFile::remove(fileName);
- }
- file = new QFile(fileName);
- QString str = "²»Äܱ£´æÎļþ %1: %2.";
- if (!file->open(QIODevice::WriteOnly)) {
- qDebug()<< str.arg(fileName).arg(file->errorString());
- delete file;
- file = 0;
- return -1;
- }
- finish = false;
- httpRequestAborted = false;
- startRequest(url);
- while(!finish)
- QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
- return retCode;
- }
- void HttpDownload::startRequest(QUrl url)
- {
- reply = qnam.get(QNetworkRequest(url));
- connect(reply, SIGNAL(finished()),
- this, SLOT(httpFinished()));
- connect(reply, SIGNAL(readyRead()),
- this, SLOT(httpReadyRead()));
- connect(reply, SIGNAL(downloadProgress(qint64,qint64)),
- this, SLOT(updateDataReadProgress(qint64,qint64)));
- }
- void HttpDownload::httpFinished()
- {
- if (httpRequestAborted) {
- if (file) {
- file->close();
- file->remove();
- delete file;
- file = 0;
- }
- reply->deleteLater();
- retCode = -1;
- finish = true;
- return;
- }
- file->flush();
- file->close();
- finish = true;
- }
- void HttpDownload::httpReadyRead()
- {
- if (file)
- file->write(reply->readAll());
- }
- void HttpDownload::updateDataReadProgress(qint64 bytesRead, qint64 totalBytes)
- {
- if (httpRequestAborted)
- return;
- }
|