QtFtp.h 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #ifndef QTFTP_H
  2. #define QTFTP_H
  3. #include <QObject>
  4. #include <QNetworkReply>
  5. #include <QNetworkAccessManager>
  6. #include <QUrl>
  7. #include <QFile>
  8. #include <QTimer>
  9. /**
  10. * @brief 封装一个FTP类,这里没有单开一个线程,在调用线程中工作
  11. */
  12. class QtFtp : public QObject
  13. {
  14. Q_OBJECT
  15. public:
  16. explicit QtFtp(QObject* parent = nullptr);
  17. ~QtFtp();
  18. void setHostAndPort(const QString& host,int port = 21); /* 设置目标主机IP和端口 */
  19. void setUserPasswd(const QString& user,const QString& pw); /* 设置目标设备的用户名和密码 */
  20. void putFile(const QString& fileName,const QString& farPath); /* 上传文件 */
  21. void getFile(const QString& fileName,const QString &srcPath); /* 下载文件 */
  22. bool waitFinished(int msecs = 30000); /* 等待完成 */
  23. bool getResult(); /* 获取结果 */
  24. signals:
  25. void signal_uploadState(bool flag); /* 文件上传成功或失败 */
  26. void signal_downloadState(bool flag); /* 文件下载成功或失败 */
  27. void signal_uploadProgress(qint64 bytesSent, qint64 bytesTotal); /* 上传进度 */
  28. void signal_downloadProgress(qint64 bytesReceived, qint64 bytesTotal); /* 下载进度 */
  29. #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
  30. /* 将QNetworkReply的一些信号转换成自定义的信号 */
  31. void signal_error(QNetworkReply::NetworkError);
  32. #endif
  33. private slots:
  34. void do_uploadFinished(); /* 上传完成 */
  35. void do_downloadFinished(); /* 下载完成,保存文件 */
  36. void do_uploadProgress(qint64 bytesSent, qint64 bytesTotal); /* 上传进度 */
  37. void do_downloadProgress(qint64 bytesReceived, qint64 bytesTotal); /* 下载进度 */
  38. #if defined (QT_VERSION) && QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
  39. void do_ftpReplyError(QNetworkReply::NetworkError error); /* ftp发送错误槽函数 */
  40. #endif
  41. private:
  42. bool m_isFinished = false; /* 上传或下载是否完成 */
  43. bool m_result = false; /* 上传或下载是否成功 */
  44. QTimer m_timer; /* 定时器,用于等待上传或下载完成 */
  45. QUrl m_url;
  46. QFile m_file; /* 存储下载的文件 */
  47. QNetworkAccessManager m_manager;
  48. QNetworkReply* m_reply = nullptr;
  49. };
  50. #endif /* QTFTP_H */