1. 程式人生 > 其它 >Qt Http下載資料夾

Qt Http下載資料夾

技術標籤:Qt

QNetwork本身無法根據QUrl獲取到資料夾下的檔案列表資料

如果使用get請求對應資料夾路徑的url會得到一個網頁,這個網頁就包含了檔案列表,所以我們要做的,就是解析這個網頁,把這些檔案資料整理一下,再遞迴地訪問子資料夾

廢話不多說,直接上程式碼:

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QJsonObject>
#include <QEventLoop>
#include <QJsonDocument>
#include <QFile>
#include <QDir>
#include <QRegExp>

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
    void downloadFile(QUrl url,QString download_path);
    void downloadDir(QUrl path,QDir download_directory);
    void downloadDir(QUrl path,QString download_path);
private:
    QNetworkAccessManager manager;

};
#endif // WIDGET_H

widget.cpp

#include "widget.h"



Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    downloadDir(QUrl("//資料夾路徑"),QDir::current());
}

Widget::~Widget()
{
}


void Widget::downloadFile(QUrl url, QString download_path)
{
    QNetworkRequest request(url);
    QNetworkReply *reply=manager.get(request);
    QFile* file=new QFile(download_path,reply);
    if(!file->open(QFile::WriteOnly)){
        qDebug()<<"檔案開啟失敗"<<*file;
    }
    connect(reply,&QNetworkReply::readyRead,this,[file,reply](){
        file->write(reply->readAll());
    });
    connect(reply,&QNetworkReply::finished,this,[file](){
        file->close();
        file->deleteLater();
    });
}

void Widget::downloadDir(QUrl path, QDir download_directory)
{
    QEventLoop loop;
    QNetworkRequest request(path);
    QNetworkReply* reply = manager.get(request);
    connect(reply,&QNetworkReply::finished,&loop,&QEventLoop::quit);
    loop.exec();
    QString data=reply->readAll();
    QRegExp rx("href=\"(.+)\">.+(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2})");
    rx.setMinimal(true);
    int pos=QRegExp("Parent Directory").indexIn(data);
    while ((pos=rx.indexIn(data,pos))>-1) {
        pos+=rx.matchedLength();
        QString file_name=rx.cap(1);
        QUrl currentUrl=path.url()+file_name;
        QDateTime currentTime=QDateTime::fromString(rx.cap(2),"yyyy-MM-dd HH:mm");
        if(file_name.endsWith("/")){      //如果是目錄,則繼續搜尋
            if(!download_directory.exists(file_name))
                download_directory.mkdir(file_name);
            QDir child=download_directory;
            child.cd(file_name);
            downloadDir(currentUrl,child);
        }
        else{
            downloadFile(currentUrl,download_directory.filePath(file_name));
        }

    }
}

void Widget::downloadDir(QUrl path, QString download_path)
{
    downloadDir(path,QDir(download_path));
}