QtFtp.h 3.0 KB

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