Qt开源网络库[9]-下载文件

2023-03-17 15:13:02 浏览数 (2)

有用户反馈说下载文件操作太麻烦了,想了想把这个功能加上吧。只需要简单地调用download()即可轻松下载文件。

接口:

  • 设置下载操作。
代码语言:javascript复制
/* 保存为默认的文件名,会从请求头去拿文件名字,如果请求头没有则为链接最后的文本内容。*/
HttpRequest &download();

/* 指定保存的文件名字,可包含路径。*/
HttpRequest &download(const QString &file);
  • 响应回调/信号槽。
代码语言:javascript复制
HttpRequest &onDownloadSuccess(const QObject *receiver, const char *method);
HttpRequest &onDownloadSuccess(std::function<void ()> lambda);
HttpRequest &onDownloadSuccess(std::function<void (QString)> lambda);

HttpRequest &onDownloadFailed(const QObject *receiver, const char *method);
HttpRequest &onDownloadFailed(std::function<void ()> lambda);
HttpRequest &onDownloadFailed(std::function<void (QString)> lambda);

例子:

  下载本项目的最新源码。

代码语言:javascript复制
HttpClient client;
client.get("https://github.com/aeagean/QtNetworkService/archive/refs/heads/master.zip")
      .download() // 启用默认文件名字下载
      .onDownloadProgress([](qint64 bytesReceived, qint64 bytesTotal) {
          // 下载进度
          qDebug() << "bytes received: " << bytesReceived
                   << "bytes total: " << bytesTotal;
       })
      .onDownloadSuccess([](QString fileName) { qDebug()<<"download success: "<<fileName; })
      .onDownloadFailed([](QString error) { qDebug()<<"download failed: "<<error; })
      .exec();

0 人点赞