English Български 한국어فارسی

Download Data from URL

The following code snippet demonstrates how to download data as QByteArray [qt-project.org] from URL. The downloaded data can be saved as a file or converted to appropriate object. For example if an image is downloaded it can be converted to QPixmap [qt-project.org] or QImage [qt-project.org] using method loadFromData() [qt-project.org]

Please note that although the name of the class is FileDownloader the downloaded data is not saved on the disk as file!

Important Classes

.pro File

  1. QT += network

If you are targeting Symbian devices remember to add the capability for network services.

  1. symbian:TARGET.CAPABILITY += NetworkServices

filedownloader.h

  1. #ifndef FILEDOWNLOADER_H
  2. #define FILEDOWNLOADER_H
  3.  
  4. #include <QObject>
  5. #include <QByteArray>
  6. #include <QNetworkAccessManager>
  7. #include <QNetworkRequest>
  8. #include <QNetworkReply>
  9.  
  10. class FileDownloader : public QObject
  11. {
  12.     Q_OBJECT
  13. public:
  14.     explicit FileDownloader(QUrl imageUrl, QObject *parent = 0);
  15.  
  16.     virtual ~FileDownloader();
  17.  
  18.     QByteArray downloadedData() const;
  19.  
  20. signals:
  21.         void downloaded();
  22.  
  23. private slots:
  24.  
  25.     void fileDownloaded(QNetworkReply* pReply);
  26.  
  27. private:
  28.  
  29.     QNetworkAccessManager m_WebCtrl;
  30.  
  31.     QByteArray m_DownloadedData;
  32.  
  33. };
  34.  
  35. #endif // FILEDOWNLOADER_H

filedownloader.cpp

  1. #include "filedownloader.h"
  2.  
  3. FileDownloader::FileDownloader(QUrl imageUrl, QObject *parent) :
  4.     QObject(parent)
  5. {
  6.     connect(&m_WebCtrl, SIGNAL(finished(QNetworkReply*)),
  7.                 SLOT(fileDownloaded(QNetworkReply*)));
  8.  
  9.     QNetworkRequest request(imageUrl);
  10.     m_WebCtrl.get(request);
  11. }
  12.  
  13. FileDownloader::~FileDownloader()
  14. {
  15.  
  16. }
  17.  
  18. void FileDownloader::fileDownloaded(QNetworkReply* pReply)
  19. {
  20.     m_DownloadedData = pReply->readAll();
  21.     //emit a signal
  22.     pReply->deleteLater();
  23.     emit downloaded();
  24. }
  25.  
  26. QByteArray FileDownloader::downloadedData() const
  27. {
  28.     return m_DownloadedData;
  29. }

Usage

Load Pixmap from URL

  • Declare slot

  1. private slots:
  2.  
  3.     void loadImage();

  • Connect signal downloaded() to the slot

  1. QUrl imageUrl("http://qt.digia.com/Documents/1/QtLogo.png");
  2. m_pImgCtrl = new FileDownloader(imageUrl, this);
  3.  
  4. connect(m_pImgCtrl, SIGNAL(downloaded()), SLOT(loadImage()));

  • Load QPixmap from the downloaded data

  1. void MainWindow::loadImage()
  2. {
  3.     QPixmap buttonImage;
  4.     buttonImage.loadFromData(m_pImgCtrl->downloadedData());
  5. }

Categories: