qt 5.15.2 网络文件下载功能

qt 5.15.2 网络文件下载功能

#include <QCoreApplication>#include <iostream>
#include <QFile>
#include <QTextStream>
//
#include <QtCore>
#include <QtNetwork>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QUrl>
#include <QDir>
//
#include <QStringList>
#include "downloadmanager.h"
//
int printf(QString line)
{std::cout<<line.toStdString()<<std::endl;
}
int printf(int line)
{std::cout<<line<<std::endl;
}int main(int argc, char *argv[])
{QCoreApplication a(argc, argv);std::cout<<"Hello World! hsg77"<<std::endl;QString toDirPath="C:\\data\\obj\\test";DownloadManager manager;manager.setOutDir(toDirPath);//manager.append(arguments);//打开csv文件QFile file("E:\\QtProject\\objDownloadTest\\GridIdx_OBJ.csv");std::cout<<file.fileName().toStdString()<<std::endl;if(file.exists()){if(file.open(QIODevice::ReadOnly)){QTextStream in(&file);//std::cout<<"file state="<<in.atEnd()<<std::endl;while(!in.atEnd()){QString line=in.readLine();QStringList fds=line.split("	");//std::cout<<line.toStdString()<<std::endl;//printf(fds.length());//处理每一行的数据QString fileUrl=fds.at(13);printf("readydown="+fileUrl);                if(fileUrl!="FILE_URL"){//下载文件  fileUrlQUrl url(fileUrl);manager.append(url);}}//}}//file.close();std::cout<<"csv file closed"<<std::endl;//开始下载开始QObject::connect(&manager,&DownloadManager::finished,&a,&QCoreApplication::quit);return a.exec();
}

定义:下载管理类
DownloadManager.h

#ifndef DOWNLOADMANAGER_H
#define DOWNLOADMANAGER_H#include <QtNetwork>
#include <QtCore>#include "textprogressbar.h"class DownloadManager: public QObject
{Q_OBJECT
public:explicit DownloadManager(QObject *parent = nullptr);void append(const QUrl &url);void append(const QStringList &urls);static QString saveFileName(const QUrl &url,const QString outDir);void setOutDir(const QString outDir);signals:void finished();private slots:void startNextDownload();void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);void downloadFinished();void downloadReadyRead();private:bool isHttpRedirect() const;void reportRedirect();QNetworkAccessManager manager;QQueue<QUrl> downloadQueue;QNetworkReply *currentDownload = nullptr;QFile output;QElapsedTimer downloadTimer;TextProgressBar progressBar;int downloadedCount = 0;int totalCount = 0;QString outDir="";
};#endif // DOWNLOADMANAGER_H

DownloadManager.cpp

#include "downloadmanager.h"#include <QTextStream>#include <cstdio>using namespace std;DownloadManager::DownloadManager(QObject *parent): QObject(parent)
{
}void DownloadManager::append(const QStringList &urls)
{for (const QString &urlAsString : urls)append(QUrl::fromEncoded(urlAsString.toLocal8Bit()));if (downloadQueue.isEmpty())QTimer::singleShot(0, this, &DownloadManager::finished);
}void DownloadManager::append(const QUrl &url)
{if (downloadQueue.isEmpty())QTimer::singleShot(0, this, &DownloadManager::startNextDownload);downloadQueue.enqueue(url);++totalCount;
}QString DownloadManager::saveFileName(const QUrl &url,const QString outDir)
{QString path = url.path();QString basename = QFileInfo(path).fileName();QString newFilePath=outDir+"\\"+basename;return newFilePath;//if (basename.isEmpty())basename = "download";if (QFile::exists(basename)) {// already exists, don't overwriteint i = 0;basename += '.';while (QFile::exists(basename + QString::number(i)))++i;basename += QString::number(i);}return basename;
}void DownloadManager::setOutDir(const QString outDir)
{this->outDir=outDir;
}void DownloadManager::startNextDownload()
{if (downloadQueue.isEmpty()) {printf("%d/%d files downloaded successfully\n", downloadedCount, totalCount);emit finished();return;}QUrl url = downloadQueue.dequeue();QString filename = saveFileName(url,this->outDir);output.setFileName(filename);if (!output.open(QIODevice::WriteOnly)) {fprintf(stderr, "Problem opening save file '%s' for download '%s': %s\n",qPrintable(filename), url.toEncoded().constData(),qPrintable(output.errorString()));startNextDownload();return;                 // skip this download}QNetworkRequest request(url);currentDownload = manager.get(request);connect(currentDownload, &QNetworkReply::downloadProgress,this, &DownloadManager::downloadProgress);connect(currentDownload, &QNetworkReply::finished,this, &DownloadManager::downloadFinished);connect(currentDownload, &QNetworkReply::readyRead,this, &DownloadManager::downloadReadyRead);// prepare the outputprintf("Downloading %s...\n", url.toEncoded().constData());downloadTimer.start();
}void DownloadManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{progressBar.setStatus(bytesReceived, bytesTotal);// calculate the download speeddouble speed = bytesReceived * 1000.0 / downloadTimer.elapsed();QString unit;if (speed < 1024) {unit = "bytes/sec";} else if (speed < 1024*1024) {speed /= 1024;unit = "kB/s";} else {speed /= 1024*1024;unit = "MB/s";}progressBar.setMessage(QString::fromLatin1("%1 %2").arg(speed, 3, 'f', 1).arg(unit));progressBar.update();
}void DownloadManager::downloadFinished()
{progressBar.clear();output.close();if (currentDownload->error()) {// download failedfprintf(stderr, "Failed: %s\n", qPrintable(currentDownload->errorString()));output.remove();} else {// let's check if it was actually a redirectif (isHttpRedirect()) {reportRedirect();output.remove();} else {printf("Succeeded.\n");++downloadedCount;}}currentDownload->deleteLater();startNextDownload();
}void DownloadManager::downloadReadyRead()
{output.write(currentDownload->readAll());
}bool DownloadManager::isHttpRedirect() const
{int statusCode = currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();return statusCode == 301 || statusCode == 302 || statusCode == 303|| statusCode == 305 || statusCode == 307 || statusCode == 308;
}void DownloadManager::reportRedirect()
{int statusCode = currentDownload->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();QUrl requestUrl = currentDownload->request().url();QTextStream(stderr) << "Request: " << requestUrl.toDisplayString()<< " was redirected with code: " << statusCode<< '\n';QVariant target = currentDownload->attribute(QNetworkRequest::RedirectionTargetAttribute);if (!target.isValid())return;QUrl redirectUrl = target.toUrl();if (redirectUrl.isRelative())redirectUrl = requestUrl.resolved(redirectUrl);QTextStream(stderr) << "Redirected to: " << redirectUrl.toDisplayString()<< '\n';
}

定义进度条类
TextProgressBar.h

#ifndef TEXTPROGRESSBAR_H
#define TEXTPROGRESSBAR_H#include <QString>class TextProgressBar
{
public:void clear();void update();void setMessage(const QString &message);void setStatus(qint64 value, qint64 maximum);private:QString message;qint64 value = 0;qint64 maximum = -1;int iteration = 0;
};#endif // TEXTPROGRESSBAR_H

TextProgressBar.cpp

#include "textprogressbar.h"#include <QByteArray>#include <cstdio>using namespace std;void TextProgressBar::clear()
{printf("\n");fflush(stdout);value = 0;maximum = -1;iteration = 0;
}void TextProgressBar::update()
{++iteration;if (maximum > 0) {// we know the maximum// draw a progress barint percent = value * 100 / maximum;int hashes = percent / 2;QByteArray progressbar(hashes, '#');if (percent % 2)progressbar += '>';printf("\r[%-50s] %3d%% %s     ",progressbar.constData(),percent,qPrintable(message));} else {// we don't know the maximum, so we can't draw a progress barint center = (iteration % 48) + 1; // 50 spaces, minus 2QByteArray before(qMax(center - 2, 0), ' ');QByteArray after(qMin(center + 2, 50), ' ');printf("\r[%s###%s]      %s      ",before.constData(), after.constData(), qPrintable(message));}
}void TextProgressBar::setMessage(const QString &m)
{message = m;
}void TextProgressBar::setStatus(qint64 val, qint64 max)
{value = val;maximum = max;
}

–the—end—
本blog地址:http://blog.csdn.net/hsg77

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/189991.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【高效开发工具系列】Hutool Http工具类

&#x1f49d;&#x1f49d;&#x1f49d;欢迎来到我的博客&#xff0c;很高兴能够在这里和您见面&#xff01;希望您在这里可以感受到一份轻松愉快的氛围&#xff0c;不仅可以获得有趣的内容和知识&#xff0c;也可以畅所欲言、分享您的想法和见解。 推荐:kwan 的首页,持续学…

WPF使用Prism框架批量注册Page,Window,UserControl等视图组件

前言 为了提高Prism框架下面的注册视图资源的简单性和提高后期可维护性,本文将使用prism自带的通过反射来批量注册视图资源,帮助我们快速高效的完成开发任务。 我们平常注册前端视图资源,一般都是在RegisterTypes方法里面,使用IContainerRegistry 的RegisterForNavigation…

PDF转WORD

无环境的&#xff0c;windows可下载可执行文件&#xff1a;https://download.csdn.net/download/shfei10100/88588106 有python运行环境的&#xff0c;可自行运行&#xff1b; 代码如下&#xff1a; from pdf2docx import Converterimport tkinter as tk from tkinter impor…

Windows11系统下内存占用率过高如何下降

. # &#x1f4d1;前言 本文主要是win11系统下CPU占用率过高如何下降的文章&#xff0c;如果有什么需要改进的地方还请大佬指出⛺️ &#x1f3ac;作者简介&#xff1a;大家好&#xff0c;我是青衿&#x1f947; ☁️博客首页&#xff1a;CSDN主页放风讲故事 &#x1f304;每日…

每日一题:NowCower-JZ64.求1+2+3+...+n

每日一题系列&#xff08;day 10&#xff09; 前言&#xff1a; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f308; &#x1f50e…

Git and solve the problem denied to xx

创建仓库 配置Git git config user.name git config user.email git config MINGW64 /e/GithubCode $ git config --global user.name "name"MINGW64 /e/GithubCode $ git config --global user.email "mailxx.com" 生产ssh ssh-keygen -t rsa -C “xx…

选择排序以及改进方案

选择排序以及改进方案 介绍&#xff1a; 选择排序是一种简单直观的排序算法&#xff0c;它的基本思想是在未排序序列中选择最小&#xff08;或最大&#xff09;的元素&#xff0c;然后将其放在已排序序列的末尾。选择排序的过程就像是每次从待排序的元素中选择最小的一个&…

Linux:锁定部分重要文件,防止误操作

一、情景描述 比如root用户或者拥有root权限的用户&#xff0c;登陆系统后&#xff0c;通过useradd指令&#xff0c;新增一个用户。 而我们业务限制&#xff0c;只能某一个人才有权限新增用户。 那么&#xff0c;这个时候&#xff0c;我们就用chattr来锁定/etc/passwd文件&…

六、ZooKeeper Java API操作

目录 1、引入maven坐标 2、节点的操作 这里操作Zookeeper的JavaAPI使用的是一套zookeeper客户端框架 Curator ,解决了很多Zookeeper客户端非常底层的细节开发工作 。 Curator包含了几个包:

日志检索场景ES->Doris迁移最佳实践:函数篇

函数列表 函数&#xff1a;term函数功能说明&#xff1a;查询某个字段里含有某个关键词的文档参数说明&#xff1a;返回值说明&#xff1a;ES使用示例&#xff1a; {"query": {"term": {"title": "blog"}} }Doris使用示例&#xf…

使用K-means把人群分类

1.前言 K-mean 是无监督的聚类算法 算法分类&#xff1a; 2.实现步骤 1.数据加工&#xff1a;把数据转为全数字&#xff08;比如性别男女&#xff0c;转换为0 和 1&#xff09; 2.模型训练 fit 3.预测 3.代码 原数据类似这样(source&#xff1a;http:img-blog.csdnimg.cn…

CleanMyMac X2024Macos强大的系统优化工具

都说苹果的闪存是金子做的&#xff0c;这句话并非空穴来风&#xff0c;普遍都是256G起步&#xff0c;闪存没升级一个等级&#xff0c;价格都要增加上千元。昂贵的价格让多数消费者都只能选择低容量版本的mac。而低容量的mac是很难满足用户的需求的&#xff0c;伴随着时间的推移…

FL Studio2024破解版激活注册码

FL Studio2024是功能强大的音乐制作解决方案&#xff0c;使用旨在为用户提供一个友好完整的音乐创建环境&#xff0c;让您能够轻松创建、管理、编辑、混合具有专业品质的音乐&#xff0c;一切的一切都集中在一个软件中&#xff0c;只要您想&#xff0c;只要您需要&#xff0c;它…

深入浅出 Linux 中的 ARM IOMMU SMMU III

系统 I/O 设备驱动程序通常调用其特定子系统的接口为 DMA 分配内存&#xff0c;但最终会调到 DMA 子系统的 dma_alloc_coherent()/dma_alloc_attrs() 等接口。dma_alloc_coherent()/dma_alloc_attrs() 等接口通过 DMA IOMMU 的回调分配内存&#xff0c;并为经过 IOMMU 的 DMA 内…

Oracle之ORA-29275: 部分多字节字符

背景&#xff1a; 在Oracle数据库中&#xff0c;通过查询 A表所有数据&#xff0c;发现某个字段出现字符问题 SELECT * FROM A一、遇到的问题 ORA-29275: 部分多字节字符排查过程&#xff1a; 1.先定位到哪条数据有问题&#xff0c;这可以通过二分查找方式缩小查询范围 SE…

android开发:获取手机IP和UDP广播

UDP广播在通讯双方互相不知道对方IP的情况下很有用。这种情形我们也可以用遍历网段来实现&#xff0c;但是比较粗暴&#xff0c;如果网段比较大&#xff0c;不是最多256台主机的C类网段的话&#xff0c;很难做遍历。 UDP广播是解决这种问题的标准方案。 注意&#xff0c;广播和…

ChatGPT 上线一周年

一年前&#xff0c;ChatGPT 正式上线&#xff0c;这无疑是个革命性的时刻&#xff0c;仅仅 6 周&#xff0c;ChatGPT 用户量达到 1 个亿。 这一年元宇宙作为概念垃圾彻底进入下水道&#xff0c;而 ChatGPT 和 AI 则席卷全球。 仅仅这一年&#xff0c;依托于 ChatGPT&#xff…

CSS 绝对定位问题和粘性定位介绍

目录 1&#xff0c;绝对定位问题1&#xff0c;绝对定位元素的特性2&#xff0c;初始包含块问题 2&#xff0c;粘性定位注意点&#xff1a; 1&#xff0c;绝对定位问题 1&#xff0c;绝对定位元素的特性 display 默认为 block。所以行内元素设置绝对定位后可直接设置宽高。脱离…

【C++】string类模拟实现过程中值得注意的点

&#x1f440;樊梓慕&#xff1a;个人主页 &#x1f3a5;个人专栏&#xff1a;《C语言》《数据结构》《蓝桥杯试题》《LeetCode刷题笔记》《实训项目》《C》《Linux》 &#x1f31d;每一个不曾起舞的日子&#xff0c;都是对生命的辜负 目录 前言 1.有关const的使用 &#x…

3.3 路由器的远程配置

实验3.3 路由器的远程配置 一、任务描述二、任务分析三、具体要求四、实验拓扑五、任务实施&#xff08;一&#xff09;、配置通过Telnet登录系统1.RA的基本配置2.RB的基本配置3.在RA上配置Telnet用户登录界面 &#xff08;二&#xff09;、配置通过STelnet登录系统1.RA的基本配…