app_curlFunc.h 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #ifndef APP_CURLFUNC_H
  2. #define APP_CURLFUNC_H
  3. #include <QObject>
  4. #include <QString>
  5. #include <QMutex>
  6. #include <QWaitCondition>
  7. #include <QThread>
  8. #include <atomic>
  9. #include <deque>
  10. #include <curl/curl.h>
  11. class CurlFtpUploader : public QObject
  12. {
  13. Q_OBJECT
  14. public:
  15. explicit CurlFtpUploader(QObject *parent = nullptr);
  16. ~CurlFtpUploader();
  17. // 设置 FTP 参数
  18. void setFtpParams(const QString &username,
  19. const QString &password,
  20. const QString &host,
  21. int port,
  22. const QString &remotePath);
  23. // 提交上传文件(非阻塞):文件进入内部串行队列,由后台线程一张一张按提交顺序上传。
  24. // 无论来自图片队列、补录重传还是日志上传,都不会并发传输(并发会争抢FTP连接导致失败)
  25. void uploadFileAsync(const QString &localFilePath);
  26. // 补录/重传重载:携带入库时记录的父目录,据此对齐远端归档目录
  27. void uploadFileAsync(const QString &localFilePath, const QString &parentPath);
  28. signals:
  29. void downloadStart(const QString &tips);
  30. void progressChanged(double uploadedPercent, const QString &filePath); // 进度百分比 (0.0 ~ 100.0) 与上传文件路径
  31. // 完成信号: success=是否成功; filePath=对应文件(调用方据此判断是哪一张传完);
  32. // error=失败原因(成功时为空)
  33. void finished(bool success, const QString &filePath, const QString &error);
  34. void sglProgress(double val,double timeLeft,double speed); //进度信号
  35. private:
  36. // 静态回调函数(供 CURL 调用)
  37. static size_t readCallback(char *buffer, size_t size, size_t nitems, void *userdata);
  38. static int progressCallback(void *clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow);
  39. // 上传任务(一张图一条)
  40. struct UploadJob {
  41. QString localFilePath;
  42. QString parentPath;
  43. };
  44. // 提交任务到串行队列并唤醒工作线程
  45. void enqueueJob(const QString &localFilePath, const QString &parentPath);
  46. // 工作线程主循环:按FIFO顺序逐个上传
  47. void runLoop();
  48. // 内部上传逻辑
  49. void performUpload(const QString &localFilePath);
  50. // 供补录/重传使用,parentPath 为入库时记录的父目录(为空时退回按文件自身父目录推导)
  51. void performUpload(const QString &localFilePath, const QString &parentPath);
  52. // FTP 参数
  53. QString m_username;
  54. QString m_password;
  55. QString m_host;
  56. int m_port;
  57. QString m_remotePath;
  58. QString update_type;
  59. QString m_currentFilePath; // 当前正在上传的文件路径,用于进度信号携带
  60. // 串行上传队列(工作线程消费)
  61. QMutex m_jobMutex;
  62. QWaitCondition m_jobCond;
  63. std::deque<UploadJob> m_jobs;
  64. std::atomic<bool> m_stopping{false};
  65. QThread *m_worker = nullptr;
  66. };
  67. #endif // APP_CURLFUNC_H