In my program, I need to upload a file, and I came across this article:
http://www.java2s.com/Code/Cpp/Qt/DownloadfromURL.htm
This code works, but it does not fit into my program, so I transcoded it. I have not finished everything, but I have encoded the basics. However, when I test it, it appears with an error message sending message.
So far this is my code:
QtDownload.h
#include <QObject> #include <QString> #include <QNetworkAccessManager> #include <QNetworkReply> class QtDownload : public QObject { Q_OBJECT public: explicit QtDownload(); ~QtDownload(); void setTarget(const QString& t); private: QNetworkAccessManager manager; QNetworkReply* reply; QString target; void connectSignalsAndSlots(); signals: public slots: void download(); void downloadFinished(QNetworkReply* data); void downloadProgress(qint64 recieved, qint64 total); };
QtDownload.cpp
#include "qtdownload.h" #include <QUrl> #include <QNetworkRequest> #include <QFile> QtDownload::QtDownload() : QObject(0) { this->connectSignalsAndSlots(); } QtDownload::~QtDownload() { if (reply != 0) delete reply; } void QtDownload::connectSignalsAndSlots() { QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(downloadFinished(QNetworkReply*))); QObject::connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64))); } void QtDownload::setTarget(const QString &t) { this->target = t; } void QtDownload::downloadFinished(QNetworkReply *data) { QFile localFile("downloadedfile"); if (!localFile.open(QIODevice::WriteOnly)) return; localFile.write(data->readAll()); localFile.close(); delete data; data = 0; } void QtDownload::download() { QUrl url = QUrl::fromEncoded(this->target.toLocal8Bit()); QNetworkRequest request(url); this->reply = manager.get(request); } void QtDownload::downloadProgress(qint64 recieved, qint64 total) { }
main.cpp
#include "qtdownload.h" #include <QTimer> int main() { QtDownload dl; dl.setTarget("http://www.java2s.com/Code/Cpp/Qt/DownloadfromURL.htm"); QTimer::singleShot(0, &dl, SLOT(download())); }
As I said, it is not completely finished, but I want this part to work before I move on.
I am also new to Qt, so any advice would be appreciated.
c ++ qt qt4
Blair harris
source share