-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdatadownloader.cpp
78 lines (64 loc) · 1.82 KB
/
datadownloader.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include "datadownloader.h"
DataDownloader::DataDownloader(QObject *parent) :
QObject(parent)
{
connect(&manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(downloadFinished(QNetworkReply*)));
}
void DataDownloader::startDownload()
{
QUrl url("http://www.swpc.noaa.gov/ftpdir/lists/ace/ace_swepam_1m.txt");
downloadFile(url);
//qDebug() << __FILE__ << __LINE__ << __func__ ;
}
void DataDownloader::downloadFile(const QUrl &url)
{
QNetworkRequest request(url);
QNetworkReply *reply = manager.get(request);
#ifndef QT_NO_SSL
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), SLOT(sslError(QList<QSslError>)));
#endif
currentDownloads.append(reply);
}
void DataDownloader::sslError(const QList<QSslError> &sslErrors)
{
#ifndef QT_NO_SSL
foreach(const QSslError &error, sslErrors)
{
fprintf(stderr, "SSL error: %s\n", qPrintable(error.errorString()));
}
#else
Q_UNUSED(sslError)
#endif
}
void DataDownloader::saveFile(const QString &filename, QIODevice *data)
{
QFile file(filename);
if(!file.open(QIODevice::WriteOnly))
{
fprintf(stderr, "Cannot save the file %s \n", qPrintable(filename), qPrintable(file.errorString()));
}
file.write(data->readAll());
file.close();
}
QString DataDownloader::getFileName(const QUrl &url)
{
QString path = url.path();
QString name = QFileInfo(path).fileName();
return name;
}
void DataDownloader::downloadFinished(QNetworkReply *reply)
{
QUrl url = reply->url();
if(reply->error())
{
fprintf(stderr, "Download %s failed", url.toEncoded().constData(), qPrintable(reply->errorString()));
}
else
{
QString filename = getFileName(url);
saveFile(filename, reply);
}
currentDownloads.removeAll(reply);
reply->deleteLater();
emit fileDownloaded();
}