QT 使用 QNetworkAccessManager 下载文件

Posted

技术标签:

【中文标题】QT 使用 QNetworkAccessManager 下载文件【英文标题】:QT Downloading File with QNetworkAccessManager 【发布时间】:2014-10-15 22:28:29 【问题描述】:

我正在尝试使此问题中的代码正常工作。 qt - how to download and save image via http?

它创建文件,但没有数据写入它们。 我最好的猜测是与信号和插槽的连接不起作用。 我做错了什么?

主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui 
class MainWindow;


class MainWindow : public QMainWindow

    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    QString getPageImage(QString url = "");
    bool saveToDisk(const QString &filename, QIODevice *data);
    ~MainWindow();

private slots:
    void on_btnDownload_clicked();

private:
    Ui::MainWindow *ui;
;

#endif // MAINWINDOW_H

qdownload.h

#ifndef QDOWNLOADER_H
#define QDOWNLOADER_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QFile>
#include <QStringList>
#include <QDir>
#include <QDebug>

class QDownloader : public QObject

    Q_OBJECT
public:
    explicit QDownloader(QObject *parent = 0);
    virtual ~QDownloader();
    void setFile(QString fileURL, QString folderName, QString fileName);

private:
    QNetworkAccessManager *manager;
    QNetworkReply *reply;
    QFile *file;

private slots:
    void onDownloadProgress(qint64,qint64);
    void onFinished(QNetworkReply*);
    void onReadyRead();
    void onReplyFinished();
;

#endif // QDOWNLOADER_H

主窗口.cpp

   #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QNetworkAccessManager"
#include "QNetworkReply"
#include "QFile"
#include "QDebug"
#include "QUrl"
#include "QStringList"
#include "qdownloader.h"
#include <QTimer>


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)

    ui->setupUi(this);
    ui->progressBar->setVisible(false);


MainWindow::~MainWindow()

    delete ui;


void MainWindow::on_btnDownload_clicked()

    QString link = ui->txtURL->text();
    int issue = ui->sbIssue->value();
    ui->progressBar->setMaximum(issue);
    ui->progressBar->setValue(0);
    ui->progressBar->setVisible(true);
    for(int j = 1; j <= issue; j++)
        int i = 1;
        while(getPageImage(link + "/" + QString::number(j) + "/" + QString::number(i) + "/").length() > 0)
            QString filename = "http://" + getPageImage(link + "/" + QString::number(j) + "/" + QString::number(i) + "/");
            qDebug() << filename;
            QDownloader qDL;
            qDL.setFile(filename,ui->txtTitle->text() + "_" + QString::number(j),ui->txtTitle->text() + "_" + QString::number(j) + "_" + QString::number(i));
            //qDebug() << getPageImage(link + "/" + QString::number(j) + "/" + QString::number(i) + "/").length();
            i++;
        
        ui->progressBar->setValue(j);
    
    ui->progressBar->setVisible(false);



QString MainWindow::getPageImage(QString url)
    QString pic = "";
    if(url.length() > 0)
        QNetworkAccessManager manager;
        QNetworkReply *response = manager.get(QNetworkRequest(QUrl(url)));
        QEventLoop event;
        connect(response,SIGNAL(finished()),&event,SLOT(quit()));
        event.exec();
        QString html = response->readAll();

        if(html.length() > 0)
            QStringList str;
            str = html.split("\n");
            //qDebug() << url;

            for (int i = 0; i < str.size(); ++i)
                if(str.at(i).contains("id=\"mainImg\"", Qt::CaseInsensitive))

                    pic = str.at(i);
                    pic = pic.remove(QRegExp("<img[^>]*src=['|\"]",  Qt::CaseInsensitive));
                    pic = pic.remove(QString::fromStdString("//"), Qt::CaseInsensitive);
                    pic = pic.remove('"');
                    pic = pic.remove("'");
                    pic = pic.remove('<');
                    pic = pic.remove('>');
                    pic = pic.remove(';');
                    pic = pic.left(pic.length()-1);
                    //qDebug() << str.at(i);
                    //qDebug() << pic;
                
            
        else
            pic = "";
        
        //qDebug() << "Lines: " << str.size();

    else
        pic = "";
    
    return pic;

qdownload.cpp

#include "qdownloader.h"

QDownloader::QDownloader(QObject *parent) :
    QObject(parent)

    manager = new QNetworkAccessManager;


QDownloader::~QDownloader()

    manager->deleteLater();


void QDownloader::setFile(QString fileURL, QString folderName, QString fileName)


    QDir dir;
    if(dir.exists(folderName))
        //qDebug() << "Existis: " + folderName;
    else
        dir.mkdir(folderName);
        //() << "Created: " + folderName;
    

    QString filePath = fileURL;
    QStringList filePathList = filePath.split('/');
    QString fileExt = filePathList.at(filePathList.count() - 1);
    fileExt = "jpg";
    QString saveFilePath;
    saveFilePath = QString(folderName + "/" + fileName + "." + fileExt );



    QNetworkRequest request;
    request.setUrl(QUrl(fileURL));
    reply = manager->get(request);



    file = new QFile;
    file->setFileName(saveFilePath);


    connect(reply,SIGNAL(downloadProgress(qint64,qint64)),this,SLOT(onDownloadProgress(qint64,qint64)));
    connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(onFinished(QNetworkReply*)));
    connect(reply,SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    connect(reply,SIGNAL(finished()),this,SLOT(onReplyFinished()));


void QDownloader::onDownloadProgress(qint64 bytesRead,qint64 bytesTotal)

    qDebug(QString::number(bytesRead).toLatin1() +" - "+ QString::number(bytesTotal).toLatin1());


void QDownloader::onFinished(QNetworkReply * reply)

    switch(reply->error())
    
        case QNetworkReply::NoError:
        
            qDebug("file is downloaded successfully.");
        break;
        default:
            qDebug(reply->errorString().toLatin1());
        ;
    

    if(file->isOpen())
    
        file->close();
        file->deleteLater();
    


void QDownloader::onReadyRead()

    qDebug() << "Ready";
    file->open(QIODevice::WriteOnly);
    file->write(reply->readAll());


void QDownloader::onReplyFinished()

    if(file->isOpen())
    
        file->close();
        file->deleteLater();
    

【问题讨论】:

@lpapp,请仔细检查。我认为这不会回答这个问题。 @mhcuervo:为了您的高兴,我重新打开了它,但在我看来,这是边界线。 【参考方案1】:

我准备了一个非常基本的例子,你可以作为参考。

在“我的”下载器的某个地方,我启动了请求:

QNetworkRequest request;
request.setUrl(org);
_reply = _manager->get(request); // Manager is my QNetworkAccessManager
connect(_reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(error(QNetworkReply::NetworkError)));
connect(_reply, SIGNAL(downloadProgress(qint64, qint64)),
            this, SLOT(updateProgress(qint64, qint64)));
connect(_reply, SIGNAL(finished()),
            this, SLOT(finished()));

如您所见,您需要做的就是get() 并正确使用QNetworkReply 的信号。 关注“我的”插槽:

void MyDownloader::error(QNetworkReply::NetworkError err)

    // Manage error here.
    _reply->deleteLater();


void MyDownloader::updateProgress(qint64 read, qint64 total)

    // This is where you can use the progress info for, lets say, update a progress bar:
    // progressBar->setMaximum(total);
    // progressBar->setValue(read);


void MyDownloader::finished()

    // Save the image here
    QByteArray b = _reply->readAll();
    QFile file(des); // "des" is the file path to the destination file
    file.open(QIODevice::WriteOnly);
    QDataStream out(&file);
    out << b;
    _reply->deleteLater();
    // done

请注意,您可以写入updateProgress() 中的文件,而不是在回复完成后立即写入整个文件。


要在updateProgress() 上写作,请在get 时间打开和/或创建QFile。然后在每次更新时使用回复的readAll 并将读取的数据写入文件,然后在finished 时关闭文件。

// ...
    _file = new QFile(des);
    _reply = _manager->get(request);
/// ...

void MyDownloader::updateProgress(qint64 read, qint64 total)

    QByteArray b = _reply->readAll();
    QDataStream out(_file);
    out << b;


void MyDownloader::finished()

    // Done
    _reply->deleteLater();
    _file->close();
    // probably delete the file object too

【讨论】:

如何在 updateProgress() 函数中写入文件? QNetworkRequest请求下已经有reply = manager->get(request); request.setUrl(QUrl(fileURL));回复 = manager->get(request); 谢谢,我更新了我的代码以在下载过程中编写。但是,问题似乎出在信号和插槽上。出于某种原因,他们没有开火。我在每个插槽中都有一个 qDebug,并且在程序运行时它们都没有出现。 您使用的是哪个版本的 Qt? Qt Creator 3.2.1(开源)基于 Qt 5.3.2(MSVC 2010,32 位)于 2014 年 9 月 14 日 04:14:50 构建,来自修订版 602746950b 版权所有 2008-2014 Digia Plc。版权所有。该程序按原样提供,不提供任何形式的保证,包括对设计、适销性和特定用途适用性的保证。

以上是关于QT 使用 QNetworkAccessManager 下载文件的主要内容,如果未能解决你的问题,请参考以下文章

一Qt初尝试,做一个QT计算器《QT 入门到实战》

使用 Qt 插件管理 Qt 对象

Qt:如何使用 QT 复制大数据?

一Qt初尝试,做一个QT计算器《QT 入门到实战》

一Qt初尝试,做一个QT计算器《QT 入门到实战》

一Qt初尝试,做一个QT计算器《QT 入门到实战》