Evgenii Legotckoi
Evgenii LegotckoiMay 25, 2018, 2:08 a.m.

Qt/C++ Tutorial 080. Downloading large files with QNetworkAccessManager

After the question appeared on the forum about downloading large files using the Qt library, I raised some of my projects and prepared a more detailed manual using this functionality. Moreover, the problem with downloading files was related to redirects. By default, QNetworkAccessManager does not switch to redirects for downloading files and retrieving pages, so you need to set the appropriate attribute in the request, then everything will work, but let's take a closer look.

The application will have the following functionality.

  • QLineEdit for entering the destination URL for downloading
    QLineEdit to enter the target directory for download in readOnly mode. We will fill it with QFileDialog.
    QProgressBar, which will show the progress of the download
    Button to cancel download

Look our downloader will be so


Project Structure

The project consists of

  • FileDownloader.pro - project profile
  • Downloader.h - Header file for downloading files
  • Downloader.cpp - Class implementation file for downloading files
  • Widget.h - Application window header file
  • Widget.cpp - Application window implementation file
  • Widget.ui - Graphical form of the application window
  • main.cpp - The file with the main application function

FileDownloader.pro, main.cpp, Widget.ui will not be considered, the first two are created by default, the latter is created through the Qt Designer graphic editor, look at it in the project itself, which is attached to the article at the very end.

Widget.h

In the header file, all the unimaginable slots for processing the interface buttons are declared and also the class for downloading files is declared on the stack

#ifndef WIDGET_H
#define WIDGET_H

#include "Downloader.h"

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    // Slot for download start
    void onDownloadButtonClicked();

    // Slot for selecting the download directory
    void onSelectTargetFolderButtonClicked();

    // Slot for canceling the download
    void onCancelButtonClicked();

    // Slot for updating download progress
    void onUpdateProgress(qint64 bytesReceived, qint64 bytesTotal);

private:
    Ui::Widget *ui;
    Downloader m_downloader; // Download Class
};

#endif // WIDGET_H

Widget.cpp

#include "Widget.h"
#include "ui_Widget.h"

#include <QFileDialog>
#include <QStandardPaths>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    // Connect to slots
    connect(ui->downloadPushButton, &QPushButton::clicked, this, &Widget::onDownloadButtonClicked);
    connect(ui->selectTargetFolderPushButton, &QPushButton::clicked, this, &Widget::onSelectTargetFolderButtonClicked);
    connect(ui->cancelPushButton, &QPushButton::clicked, this, &Widget::onCancelButtonClicked);
    connect(&m_downloader, &Downloader::updateDownloadProgress, this, &Widget::onUpdateProgress);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::onDownloadButtonClicked()
{
    // We start downloading the file by passing the 
    // path to the directory where we will upload files, 
    // url, where the file is located
    m_downloader.get(ui->targetFolderLineEdit->text(), ui->urlLineEdit->text());
}

void Widget::onSelectTargetFolderButtonClicked()
{
    // Selecting the destination directory for downloading
    QString targetFolder = QFileDialog::getExistingDirectory(this,
                                                             tr("Select folder"),
                                                             QStandardPaths::writableLocation(QStandardPaths::DownloadLocation),
                                                             QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    ui->targetFolderLineEdit->setText(targetFolder);
}

void Widget::onCancelButtonClicked()
{
    // Cancel upload
    m_downloader.cancelDownload();
    ui->downloadProgressBar->setMaximum(100);
    ui->downloadProgressBar->setValue(0);
}

void Widget::onUpdateProgress(qint64 bytesReceived, qint64 bytesTotal)
{
    // Updating upload progress
    ui->downloadProgressBar->setMaximum(bytesTotal);
    ui->downloadProgressBar->setValue(bytesReceived);
}

Downloader.h

And now look at the class for downloading files, taking into account the progress of the download.

An important point is that large files need to be processed gradually, they can not be read by one query. Therefore, you need to handle the QNetworkReply::readyRead signal from the object of the current response to the request. This signal is emitted when the buffer contains data that we can assume.

And only after the download is completed QNetworkAccessManager will issue a finished signal, which will close the file and complete the connection with the removal of the object of the current response to the request.

#ifndef DOWNLOADER_H
#define DOWNLOADER_H

#include <QNetworkAccessManager>

class QNetworkReply;
class QFile;

class Downloader : public QObject
{
    Q_OBJECT
    using BaseClass = QObject;

public:
    explicit Downloader(QObject* parent = nullptr);

    // Method for starting the download
    bool get(const QString& targetFolder, const QUrl& url);

public slots:
    // Method of canceling the load
    void cancelDownload();

signals:
    // A signal that sends information about the progress of the download
    void updateDownloadProgress(qint64 bytesReceived, qint64 bytesTotal);

private slots:
    // Slot for gradual reading of downloaded data
    void onReadyRead();
    // Slot for processing request completion
    void onReply(QNetworkReply* reply);

private:
    QNetworkReply* m_currentReply {nullptr};    // Current request being processed
    QFile* m_file                 {nullptr};    // The current file to which the entry is being written
    QNetworkAccessManager m_manager;            // Network manager for downloading files
};

#endif // DOWNLOADER_H

Downloader.cpp

#include "Downloader.h"

#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFile>
#include <QDir>

Downloader::Downloader(QObject* parent) :
    BaseClass(parent)
{
    // Connect to the finished signal
    connect(&m_manager, &QNetworkAccessManager::finished, this, &Downloader::onReply);
}

bool Downloader::get(const QString& targetFolder, const QUrl& url)
{
    if (targetFolder.isEmpty() || url.isEmpty())
    {
        return false;
    }

    // Create object of file class for download
    // Here there is a target directory and the name of the file that is allocated from the URL
    m_file = new QFile(targetFolder + QDir::separator() + url.fileName());
    // Trying to open the file
    if (!m_file->open(QIODevice::WriteOnly))
    {
        delete m_file;
        m_file = nullptr;
        return false;
    }

    // Creating a request
    QNetworkRequest request(url);
    // Allow to go on redirects
    request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    // Running the download
    m_currentReply = m_manager.get(request);

    // After that, we immediately connect to signals about readiness of data to read and update the progress of downloading
    connect(m_currentReply, &QNetworkReply::readyRead, this, &Downloader::onReadyRead);
    connect(m_currentReply, &QNetworkReply::downloadProgress, this, &Downloader::updateDownloadProgress);
    return true;
}

void Downloader::onReadyRead()
{
    // If there is data and the file is open
    if (m_file)
    {
        // write them to a file
        m_file->write(m_currentReply->readAll());
    }
}

void Downloader::cancelDownload()
{
    // Cancel request
    if (m_currentReply)
    {
        m_currentReply->abort();
    }
}

void Downloader::onReply(QNetworkReply* reply)
{
    // by completion of the request
    if (reply->error() == QNetworkReply::NoError)
    {
        // save file
        m_file->flush();
        m_file->close();
    }
    else
    {
        // Or delete it in case of error
        m_file->remove();
    }

    delete m_file;
    m_file = nullptr;
    reply->deleteLater();
}

Conclusion

Thus, we have an application that can download the required file for a given URL and place it in the target directory.

Link to download the project Downloader

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

f
  • May 31, 2018, 4:08 p.m.

не могу понять как обработать ошибку некорректной ссылки?
Пример: "ftp://cddis.gsfc.nasa.gov/pub/slr/data/npt_crd/gracea/2010/gracea_20100101.npt.Z"

Evgenii Legotckoi
  • June 1, 2018, 10:59 a.m.

У вас скорее всего ошибка превышения интервала ожидания - QNetworkReply::TimeoutError

Гляньте вот эту статью про описание ошибок QNetworkAccessManager
Там в конце статьи есть пример обработки ошибок с выводом в qDebug()
f
  • June 6, 2018, 12:42 p.m.

у меня никак не получается обработать ошибку некорректной ссылки(

    connect(&m_downloader.manager, &QNetworkAccessManager::finished, this, &Widget::onResult);
    connect(m_downloader.currentReply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &Widget::errorSlot);
R
  • June 7, 2018, 12:21 a.m.

Здравствуйте. В вашем примере не обновляется прогресс-бар. А если точнее - он выставляет 100% после закачки, и всё. Во время самой закачки просто 0%. Сомневаюсь что так задумано, но всё же, как сделать чтобы обновлялся каждый кусок?

Evgenii Legotckoi
  • June 7, 2018, 2:44 a.m.

Какого размера пробуете скчивать файлы и на какой скорости у вас работает интернет.
Есть ещё один неприятный момент в том, что не на всех платформах правильно передаётся информация о прогрессе закачки.
Так что какую используете операционную систему?

Evgenii Legotckoi
  • June 7, 2018, 2:46 a.m.

А почему вы не сделаете обработку ошибок в слоте onResult.

Кстати, по поводу кастов перегруженных сигналов и слотов. Посмотрите на использование Overload шаблона , ппроще писать перегруженные сигнал/слотовые соединения будет.
R
  • June 7, 2018, 3:28 a.m.

Проблема была в ресурсе, с которого скачиваю. Пытался тянуть с google disc - а там ограничение 25мб на прямые ссылки. Поэтому он и втупал.


Можете подсказать какие-нибудь ресурсы, на которых есть возможность обновлять файл (контроль версий), и при этом ссылка на него останется та же. Ну и без ограничений как у гугла, буду очень благодарен.
Evgenii Legotckoi
  • June 7, 2018, 3:32 a.m.

ну.. хз.. Github может быть, там вам и контроль версии и всё остальное, вроде и ссылки на метки прямые.

Ну или поднимите свой онлайн ресурс ))
Если честно, понятия не имею, не было такой необходимости, а если и была, то объодился ресурсами своего сайта.
F
  • Sept. 20, 2019, 11:25 a.m.

вызываю метод get у m_downloader в другом методе и приложение начинает вылетать. В чем ошибка?

Evgenii Legotckoi
  • Sept. 25, 2019, 3:52 a.m.

Это дебажить нужно, может быть что угодно.

v
  • Oct. 29, 2019, 9:40 a.m.

Здпавствуйте Евгений.
Прошу совета, вот из-за этой строчки кода:
connect(&m_manager, &QNetworkAccessManager::finished, this, &Downloader::onReply);

Выдает такую ошибку: D:\Qt\5.10.1\mingw53_32\include\QtCore\qglobal.h:762: ошибка: static assertion failed: Signal and slot arguments are not compatible.
#define Q_STATIC_ASSERT_X(Condition, Message) static_assert(bool(Condition), Message)
Что это может быть?

Evgenii Legotckoi
  • Oct. 29, 2019, 9:51 a.m.

Добрый день.
Вы полностью скопировали тот код? Или самостоятельно писали свой вариант, посматривая в эту статью?

Выглядит так, что у вас несовместимый сигнал со слотом.

Покажите сигнатуру метода Downloader::onReply

v
  • Oct. 29, 2019, 9:56 a.m.
  • (edited)

Писал свой вариант, вот сигнатура метода Downloader::onReply:

void onReply(QNetworkReply& reply);

void Downloader::onReply(QNetworkReply &reply)
{
    if(reply.error() == QNetworkReply::NoError){
        m_file->flush();
        m_file->close();
    }
    else{
        m_file->remove();
    }

    delete m_file;
    m_file = nullptr;
    reply.deleteLater();
}
v
  • Oct. 29, 2019, 9:57 a.m.

Точнее будет сказать что я набивал руками Ваш код)))

Evgenii Legotckoi
  • Oct. 29, 2019, 10:02 a.m.
  • (edited)

Понятно )) Вы допустили ошибку.

Вот ваша строчка

void Downloader::onReply(QNetworkReply &reply)

Вот моя строчка

void Downloader::onReply(QNetworkReply *reply)

В вашем случае используется ссылка, а в моём случае указатель. Это разные вещи.

Используйте, пожалуйста, диалог вставки программного кода. Это кнопка с символом <> в редакторе.
Дело в том, что в редакторе комментариев используется markdown синтаксис, поэтому нужна специальная разметка кода. Диалог добавляет её автоматически.

v
  • Oct. 29, 2019, 10:08 a.m.

))) Спасибо Евгений! Впреть буду внимательнее)))

m
  • Feb. 9, 2020, 9:44 a.m.

Дня доброго.
Прочитал ваш урок. Вроде все понял. Но взялся реализовывать этот принцип в своем проекте(загрузка файлов на фтп) и уперся что не могу понять как реализовать progressbar.
вот код:

void MainWindow::copyToFtp(QString Fname)
{
    ui->progressBar->show();
    fFileFTP =new QFile (Fname);
    QFileInfo fileInfoFTP(fFileFTP->fileName());
    QUrl url("ftp://ftp.ihostfull.com/htdocs/"+fileInfoFTP.completeBaseName()+"."+fileInfoFTP.suffix());
    url.setPort(21);
    url.setPassword("------");
    url.setUserName("-------");
    fFileFTP->open(QIODevice::ReadOnly);
    QNetworkAccessManager manager(0);
    QNetworkReply *reply = manager.put(QNetworkRequest(url),fFileFTP);
    QEventLoop loop;
    QObject::connect(reply,SIGNAL(finished()),&loop,SLOT(quit()));
    loop.exec();
    fFileFTP->close();
}

Как сюда интегрировать progressBar?
Сделайте поправку что новичек в програмированнии.

Evgenii Legotckoi
  • Feb. 10, 2020, 3:02 a.m.

Реализуйте сначала правильно закачку по ftp. А потом уже внедряйте прогресс бар.

Ошибки, которые сразу бросаются в глаза

  • QNetworkAccessManager manager(0); - объявлено локально внутри метода, в моём примере на тсеке класса. Конечно правильно, что вы петлёй тормозите выход из метода, но при этом полностью уничтожаете преимущество ассинхронности QNetworkAccessManager
  • QObject::connect(reply,SIGNAL(finished()),&loop,SLOT(quit())); - Использование устревшего синтаксиса сигналов и слотов. В этой статье используется новый синтаксис.

Вообще ваш код сам по себе работает? Если работает, то сначала реализуйте как в статье, чтобы без QEventLoop было. Поскольку этой петлёй вы морозите GUI, скорее всего поэтому ничего и не работает.

m
  • Feb. 10, 2020, 3:06 a.m.

Код сам по себе работает. Файлы на фтп грузяться.

Evgenii Legotckoi
  • Feb. 10, 2020, 3:15 a.m.
  • (edited)

QEventLoop скорее всего морозит GUI, поскольку тормозит выполнение всего остального программного кода в приложении, ожидая выполнения работы QNetworkAccessManager. Вам нужно переписать так, как показано в примере. Тем более, что QNetworkAccessManager может выполнять несколько запросов одновременно и асинхронно. Нет нужды создавать объект QNetworkAccessManager в каждом слоте. Тем более, что более одного при таком подходе вы не создадите. GUI просто не будет реагировать на событие мыши, пока не выполнится загрузка.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 23, 2024, 3:51 p.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks