Qt 实现ftp工具类,Qt C++代码
时间: 2024-04-28 16:26:55 浏览: 195
以下是一个简单的Qt实现FTP工具类的代码示例:
FTPManager.h 文件:
```cpp
#ifndef FTPMANAGER_H
#define FTPMANAGER_H
#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QUrl>
#include <QFile>
#include <QFileInfo>
class FTPManager : public QObject
{
Q_OBJECT
public:
explicit FTPManager(QObject *parent = nullptr);
void uploadFile(const QString &filePath, const QUrl &url, const QString &userName, const QString &password);
void downloadFile(const QUrl &url, const QString &userName, const QString &password);
private slots:
void uploadProgress(qint64 bytesSent, qint64 bytesTotal);
void downloadProgress(qint64 bytesReceived, qint64 bytesTotal);
void finished(QNetworkReply *reply);
private:
QNetworkAccessManager *m_manager;
QFile *m_file;
};
#endif // FTPMANAGER_H
```
FTPManager.cpp 文件:
```cpp
#include "FTPManager.h"
FTPManager::FTPManager(QObject *parent) : QObject(parent)
{
m_manager = new QNetworkAccessManager(this);
}
void FTPManager::uploadFile(const QString &filePath, const QUrl &url, const QString &userName, const QString &password)
{
m_file = new QFile(filePath);
if (!m_file->exists()) {
qDebug() << "File not found!";
return;
}
m_file->open(QIODevice::ReadOnly);
QNetworkRequest request(url);
request.setUserName(userName);
request.setPassword(password);
QNetworkReply *reply = m_manager->put(request, m_file);
connect(reply, SIGNAL(uploadProgress(qint64,qint64)), this, SLOT(uploadProgress(qint64,qint64)));
connect(reply, SIGNAL(finished()), this, SLOT(finished()));
}
void FTPManager::downloadFile(const QUrl &url, const QString &userName, const QString &password)
{
QNetworkRequest request(url);
request.setUserName(userName);
request.setPassword(password);
QNetworkReply *reply = m_manager->get(request);
connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));
connect(reply, SIGNAL(finished()), this, SLOT(finished()));
}
void FTPManager::uploadProgress(qint64 bytesSent, qint64 bytesTotal)
{
qDebug() << "Uploading file" << m_file->fileName() << "Progress:" << bytesSent << "/" << bytesTotal;
}
void FTPManager::downloadProgress(qint64 bytesReceived, qint64 bytesTotal)
{
qDebug() << "Downloading file Progress:" << bytesReceived << "/" << bytesTotal;
}
void FTPManager::finished(QNetworkReply *reply)
{
if (reply->error()) {
qDebug() << "Error:" << reply->errorString();
}
else {
qDebug() << "Finished!";
}
reply->deleteLater();
m_file->close();
}
```
使用示例:
```cpp
FTPManager ftpManager;
QUrl url("ftp://example.com/upload/file.txt");
QString userName = "username";
QString password = "password";
QString filePath = "/path/to/local/file.txt";
ftpManager.uploadFile(filePath, url, userName, password);
// 或者下载文件
// ftpManager.downloadFile(url, userName, password);
```
这个示例实现了FTP文件上传和下载功能,并且可以在控制台中输出上传和下载的进度。您可以根据需要进行更改和完善。
阅读全文