我怎么能在Qt从互联网上下载文件?

时间:2011-10-23 23:25:14

标签: c++ qt file download

我不知道问题是什么...编译器(Qt)运行程序没有错误,但文件没有下载... 你能告诉我请告诉我哪里错了吗?

我通过示例“download”制作,它位于qt文件夹中。唯一的区别是他们有一个控制台,我有Windows应用程序。

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtNetwork>
#include <QMainWindow>

namespace Ui {

    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButton_clicked();

private:
    Ui::MainWindow *ui;
};

class DownloadManager: public QObject
{
    Q_OBJECT
    QNetworkAccessManager manager;
    QList<QNetworkReply *> currentDownloads;

public:
    DownloadManager();
    void doDownload(const QUrl &url);
    QString saveFileName(const QUrl &url);
    bool saveToDisk(const QString &filename, QIODevice *data);

public slots:
    void execute();
    void downloadFinished(QNetworkReply *reply);
};


#endif // MAINWINDOW_H

的main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QtNetwork>
#include <QNetworkAccessManager>
#include <QStringList>
#include <QCoreApplication>
#include <QFile>
#include <QFileInfo>
#include <QList>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QStringList>
#include <QTimer>
#include <QUrl>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
#if defined(Q_WS_S60)
    w.showMaximized();
#else
    w.show();
#endif

    return a.exec();
}

DownloadManager::DownloadManager()
{
    connect(&manager, SIGNAL(finished(QNetworkReply*)),
            SLOT(downloadFinished(QNetworkReply*)));
}

void DownloadManager::doDownload(const QUrl &url)
{
    QNetworkRequest request(url);
    QNetworkReply *reply = manager.get(request);

    currentDownloads.append(reply);
}

QString DownloadManager::saveFileName(const QUrl &url)
{
    QString path = url.path();
    QString basename = QFileInfo(path).fileName();

    if (basename.isEmpty())
        basename = "download";

    if (QFile::exists(basename)) {
        // already exists, don't overwrite
        int i = 0;
        basename += '.';
        while (QFile::exists(basename + QString::number(i)))
            ++i;

        basename += QString::number(i);
    }

    return basename;
}

bool DownloadManager::saveToDisk(const QString &filename, QIODevice *data)
{
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly)) {
        fprintf(stderr, "Could not open %s for writing: %s\n",
                qPrintable(filename),
                qPrintable(file.errorString()));
        return false;
    }

    file.write(data->readAll());
    file.close();

    return true;
}

void DownloadManager::execute()
{
    QStringList args = QCoreApplication::instance()->arguments();
    args[0]="http://www.google.ru/images/srpr/logo3w.png";

QString arg=args[0];

        QUrl url = QUrl::fromEncoded(arg.toLocal8Bit());
        doDownload(url);

}

void DownloadManager::downloadFinished(QNetworkReply *reply)
{
    QUrl url = reply->url();
    if (reply->error()) {
        fprintf(stderr, "Download of %s failed: %s\n",
                url.toEncoded().constData(),
                qPrintable(reply->errorString()));
    } else {
        QString filename = saveFileName(url);
        if (saveToDisk(filename, reply))
            printf("Download of %s succeded (saved to %s)\n",
                   url.toEncoded().constData(), qPrintable(filename));
    }

    currentDownloads.removeAll(reply);
    reply->deleteLater();

    if (currentDownloads.isEmpty())
      //   all downloads finished
        QCoreApplication::instance()->quit();
}

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

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


void MainWindow::on_pushButton_clicked()
{
    DownloadManager manager;

    manager.execute();
    QTimer::singleShot(0, &manager, SLOT(execute()));
}

1 个答案:

答案 0 :(得分:4)

问题在于您的代码:

void MainWindow::on_pushButton_clicked()
{
    DownloadManager manager;    
    manager.execute();
}

QNetworkAccessManager是异步的,因此它需要一个事件循环来进行任何下载。但是当函数on_pushButton_clicked()返回并将控件返回给事件循环时,QNetworkAccessManager已经被销毁,并且没有时间做任何事情。

QMessageBox中添加DownloadManager::execute时,您实际上正在运行另一个包含广告位on_pushButton_clicked()的事件循环,并且它为QNetworkAccessManager提供了机会它的工作。

正确的解决方案是动态分配DownloadManager,并最终在完成所有下载后使其自行销毁。

void MainWindow::on_pushButton_clicked()
{
    DownloadManager *manager = new DownloadManager(this);    
    manager->execute();
}

void DownloadManager::downloadFinished(QNetworkReply *reply)
{
    ...
    if (currentDownloads.isEmpty())
        this->deleteLater();
}