QtFtp.h 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. * 这里的上传下载路径都是相对路径,不包含前面的IP地址和端口
  12. * 注意:目前只支持单个请求,即一个请求完成后才能进行下一个请求
  13. */
  14. class QtFtp : public QObject
  15. {
  16. Q_OBJECT
  17. public:
  18. explicit QtFtp(QObject* parent = nullptr);
  19. ~QtFtp();
  20. /* 设置目标主机IP和端口 */
  21. void setHostAndPort(const QString& host,int port = 21);
  22. /* 设置目标设备的用户名和密码 */
  23. void setUserPasswd(const QString& user,const QString& pw);
  24. /* 上传文件 */
  25. void putFile(const QString& fileName,const QString& farPath);
  26. /* 上传文件,直接上传内存数据 */
  27. void putFile(const QByteArray& data,const QString& farPath);
  28. /* 下载文件 */
  29. void getFile(const QString& fileName,const QString &srcPath);
  30. /* 下载文件,直接下载到内存,路径是相对路径,不包含前面的IP地址和端口 */
  31. void getFile(QByteArray& data,const QString& srcPath);
  32. /* 等待完成 */
  33. bool waitFinished(int msecs = 30000);
  34. /* 获取结果 */
  35. bool getResult();
  36. /* 创建目录 */
  37. bool createDir(const QString& path);
  38. signals:
  39. /* 文件上传成功或失败 */
  40. void signal_uploadState(bool flag);
  41. /* 文件下载成功或失败 */
  42. void signal_downloadState(bool flag);
  43. /* 上传进度 */
  44. void signal_uploadProgress(qint64 bytesSent, qint64 bytesTotal);
  45. /* 下载进度 */
  46. void signal_downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
  47. #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
  48. /* 将QNetworkReply的一些信号转换成自定义的信号 */
  49. void signal_error(QNetworkReply::NetworkError);
  50. #endif
  51. private slots:
  52. /* 上传完成 */
  53. void do_uploadFinished();
  54. /* 下载完成,保存文件 */
  55. void do_downloadFinished();
  56. /* 下载完成,保存数据 */
  57. void do_downloadFinishedToData();
  58. /* 上传进度 */
  59. void do_uploadProgress(qint64 bytesSent, qint64 bytesTotal);
  60. /* 下载进度 */
  61. void do_downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
  62. /* ftp其他任务完成槽函数 */
  63. void do_finished();
  64. /* 定时器超时函数 */
  65. void do_timeout();
  66. #if defined (QT_VERSION) && QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
  67. void do_ftpReplyError(QNetworkReply::NetworkError error); /* ftp发送错误槽函数 */
  68. #endif
  69. private:
  70. bool m_isFinished = false; /* 上传或下载是否完成 */
  71. bool m_result = false; /* 上传或下载是否成功 */
  72. QTimer m_timer; /* 定时器,用于等待上传或下载完成 */
  73. QUrl m_url;
  74. QFile m_file; /* 存储下载的文件 */
  75. QFile m_fileUpload; /* 存储上传的文件 */
  76. QByteArray *m_downloadData = nullptr; /* 存储下载的数据 */
  77. QNetworkAccessManager m_manager;
  78. QNetworkReply* m_reply = nullptr;
  79. };
  80. #endif /* QTFTP_H */