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));
}