QT5 实现 SFTP 上传和下载文件

1.QSsh-Botan-1: QSSH库,含有botan分支 - Gitee.com下载QSSH 源码,注意是选择botan-1分支

使用QT 编译,可以屏蔽掉 examples的编译

编译完成后将 src\libs\ssh src\libs\3rdparty\botan 头文件 拷贝至工程目录/Common/ssh

将编译好的库文件拷贝至工程目录 lib64

工程文件 添加 LIBS += -L$${PWD}/lib64 -lQSsh -lBotan
INCLUDEPATH += ./Common/ssh

2. 创建类,SecureFileUploader, examples 中已经有例子,我增加下载文件的接口

securefileuploader.h

/**************************************************************************
**
** This file is part of QSsh
**
** Copyright (c) 2012 LVK
**
** Contact: andres.pagliano@lvklabs.com
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
**************************************************************************/

#ifndef SECUREFILEUPLOADER_H
#define SECUREFILEUPLOADER_H

#include <QObject>

#include "sftpchannel.h"
#include "sshconnection.h"
#define UPLOAD      0
#define DOWNLOAD    1
/// Very simple example to upload a file using FTPS
class SecureFileUploader : public QObject
{
    Q_OBJECT
public:

    explicit SecureFileUploader(QObject *parent = 0);
    void setInfo(const QString &host, const QString &userName, const QString &passwd);
    void upload(const QString &dest,const QString &localFile);

signals:
    void sigDownLoadFinished();
    void sigUpLoadFinished();
    void loadError(int);
    void connectError();
private slots:
    void onConnected();
    void onConnectionError(QSsh::SshError);
    void onChannelInitialized();
    void onChannelError(const QString &err);
    void onOpfinished(QSsh::SftpJobId job, const QString & error = QString());

private:
    QString m_localFilename;
    QString m_remoteFilename;
    QSsh::SftpChannel::Ptr m_channel;
    QSsh::SshConnection *m_connection;
    void parseDestination(const QString &dest);

private:
    QString m_host;
    QString m_userName;
    QString m_pwd;

/*******下载*****/
public:
    void DownLoad(const QString &savePath, const QString &fname);
    void DownLoadFiles(const QString& savePath,const QStringList &fnames);
    void SftpDownLoadClient();
private:
    QString DownSavePath;
    QString DownFileName;
    QStringList DownFilenames;
    QSsh::SftpChannel::Ptr m_Downchannel;
    QSsh::SshConnection *m_Downconnection;
private slots:
    void onDownConnected();
    bool onDownLoadFile();
    void onDownLoadfinished(QSsh::SftpJobId job, const QString &err);


};

#endif // SECUREFILEUPLOADER_H

securefileuploader.cpp

/**************************************************************************
**
** This file is part of QSsh
**
** Copyright (c) 2012 LVK
**
** Contact: andres.pagliano@lvklabs.com
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
**************************************************************************/

#include "securefileuploader.h"

#include <QtDebug>
#include <QFileInfo>

SecureFileUploader::SecureFileUploader(QObject *parent) :
    QObject(parent), m_connection(0)
{
}

void SecureFileUploader::setInfo(const QString &host, const QString &userName, const QString &passwd)
{
    m_host = host;
    m_userName = userName;
    m_pwd = passwd;
}


void SecureFileUploader::upload(const QString &dest,const QString &localFile)
{
    QFileInfo info(localFile);

    m_localFilename = localFile;
    m_remoteFilename = dest + "/" + info.fileName();

    QSsh::SshConnectionParameters params;
    params.setHost(m_host);
    params.setUserName(m_userName);
    params.setPassword(m_pwd);
    params.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
    params.timeout = 30;
    params.setPort(22);

    m_connection = new QSsh::SshConnection(params, this); // TODO free this pointer!

    connect(m_connection, SIGNAL(connected()), SLOT(onConnected()));
    connect(m_connection, SIGNAL(error(QSsh::SshError)), SLOT(onConnectionError(QSsh::SshError)));

    qDebug() << "SecureUploader: Connecting to host" << m_host;

    m_connection->connectToHost();
}

void SecureFileUploader::onConnected()
{
    qDebug() << "SecureUploader: Connected";
    qDebug() << "SecureUploader: Creating SFTP channel...";

    m_channel = m_connection->createSftpChannel();

    if (m_channel) {
        connect(m_channel.data(), SIGNAL(initialized()),
                SLOT(onChannelInitialized()));
        connect(m_channel.data(), SIGNAL(initializationFailed(QString)),
                SLOT(onChannelError(QString)));
        connect(m_channel.data(), SIGNAL(finished(QSsh::SftpJobId, QString)),
                SLOT(onOpfinished(QSsh::SftpJobId, QString)));

        m_channel->initialize();

    } else {
        qDebug() << "SecureUploader: Error null channel";
    }
}

void SecureFileUploader::onConnectionError(QSsh::SshError err)
{
    qDebug() << "SecureUploader: Connection error" << err;
    emit connectError();
}

void SecureFileUploader::onChannelInitialized()
{
    qDebug() << "SecureUploader: Channel Initialized";
    qDebug()<<"m_localFilename:"<<m_localFilename<<"\n";
    qDebug()<<"m_remoteFilename:"<<m_remoteFilename<<"\n";
    QSsh::SftpJobId job = m_channel->uploadFile(m_localFilename, m_remoteFilename,
                                                QSsh::SftpOverwriteExisting);

    if (job != QSsh::SftpInvalidJob) {
        qDebug() << "SecureUploader: Starting job #" << job;
    } else {
        emit loadError(UPLOAD);
        qDebug() << "SecureUploader: Invalid Job";
    }
}

void SecureFileUploader::onChannelError(const QString &err)
{
    qDebug() << "SecureUploader: Error: " << err;
}

void SecureFileUploader::onOpfinished(QSsh::SftpJobId job, const QString &err)
{
    qDebug() << "SecureUploader: Finished job #" << job << ":" << (err.isEmpty() ? "OK" : err);
    emit sigUpLoadFinished();
}


void SecureFileUploader::DownLoad(const QString &savePath, const QString &fname)
{
    DownSavePath = savePath;
    DownFileName = fname;
    SftpDownLoadClient();
}

void SecureFileUploader::DownLoadFiles(const QString &savePath, const QStringList &fnames)
{
    DownSavePath = savePath;
    DownFilenames = fnames;
    DownFileName = DownFilenames.takeFirst();
    SftpDownLoadClient();
}

void SecureFileUploader::SftpDownLoadClient()
{

    QSsh::SshConnectionParameters params;
    params.setHost(m_host);
    params.setUserName(m_userName);
    params.setPassword(m_pwd);
    params.authenticationType = QSsh::SshConnectionParameters::AuthenticationTypePassword;
    params.timeout = 30;
    params.setPort(22);

    m_Downconnection = new QSsh::SshConnection(params, this); // TODO free this pointer!
    connect(m_Downconnection, SIGNAL(connected()), SLOT(onDownConnected()));
    connect(m_Downconnection, SIGNAL(error(QSsh::SshError)), SLOT(onConnectionError(QSsh::SshError)));
    qDebug() << "SecureUploader: Connecting to host" << m_host;
    m_Downconnection->connectToHost();
}
void SecureFileUploader::onDownConnected(){
    qDebug() << "SecureUploader: onDownConnected Connected";
    qDebug() << "SecureUploader: onDownConnected Creating SFTP channel...";
    m_Downchannel = m_Downconnection->createSftpChannel();

    if (m_Downchannel) {
        connect(m_Downchannel.data(), SIGNAL(initialized()),
                SLOT(onDownLoadFile()));
        connect(m_Downchannel.data(), SIGNAL(initializationFailed(QString)),
                SLOT(onChannelError(QString)));
        connect(m_Downchannel.data(), SIGNAL(finished(QSsh::SftpJobId, QString)),
                SLOT(onDownLoadfinished(QSsh::SftpJobId, QString)));
        m_Downchannel->initialize();
    } else {
        qDebug() << "SecureUploader: Error null channel";
    }
}
bool SecureFileUploader::onDownLoadFile()
{
    qDebug() << "SecureUploader: onDownLoadFile Channel Initialized";
    QFileInfo fileInfo(DownFileName);
    QString SftpSavePath  = DownSavePath;
#ifdef Q_OS_LINUX
    SftpSavePath += "/";
#else
    SftpSavePath += "\\";
#endif
    SftpSavePath += fileInfo.fileName();
    QSsh::SftpJobId job = m_Downchannel->downloadFile(DownFileName,SftpSavePath,QSsh::SftpOverwriteExisting);
    if (job != QSsh::SftpInvalidJob) {
        qDebug() << "SecureUploader: Starting job #" << job;
        return true;
    } else {
        emit loadError(DOWNLOAD);
        qDebug() << "SecureUploader: Invalid Job";
        return false;
    }
    return false;
}

void SecureFileUploader::onDownLoadfinished(QSsh::SftpJobId job, const QString &err)
{
    qDebug() << "SecureUploader: Finished DownLoad job #" << job << ":" << (err.isEmpty() ? "OK" : err);
    if(err.compare("No such file",Qt::CaseSensitive)==0){
        QFileInfo fileInfo(DownFileName);
        QString SftpSavePath  = DownSavePath;
#ifdef Q_OS_LINUX
        SftpSavePath += "/";
#else
        SftpSavePath += "\\";
#endif
        SftpSavePath += fileInfo.fileName();

        QFile fileremove(SftpSavePath);
        fileremove.remove();
    }
    if (DownFilenames.isEmpty())
    {
        delete m_Downconnection;
        m_Downconnection = NULL;
        emit sigDownLoadFinished();
    }
    else
    {
        DownFileName = DownFilenames.takeFirst();
        onDownLoadFile();
    }
}




在对 SecureFileUploader 进一步封装 SZRSFtpTools

SZRSFtpTools.h

#ifndef SZRSFTPTOOLS_H
#define SZRSFTPTOOLS_H
#include <QString>
#include <QObject>



#define SFTP_UPLOAD      0
#define SFTP_DOWNLOAD    1

class SecureFileUploader;
class Q_DECL_EXPORT SZRSFtpTools: public QObject
{
    Q_OBJECT
public:
    SZRSFtpTools(QObject* parent = NULL);
    ~SZRSFtpTools();
    void setSftpInfo(const QString& host,const QString& userName,const QString& pwd);
    void downLoadFile(const QString &savePath, const QString &fname);
    void downLoadFiles(const QString &savePath, const QStringList &fnames);
    void uploadFile(const QString &savePath, const QString &fname);

signals:
    void DownloadFinished();
    void UploadFinished();
    void LoadFiled(int);
    void connectError();
private:
    QString m_host;
    QString m_userName;
    QString m_pwd;
    SecureFileUploader* m_sftp;
};

#endif // SZRSFTPTOOLS_H

SZRSFtpTools.cpp

#include "SZRSFtpTools.h"
#include "securefileuploader.h"
#include <windows.h>


SZRSFtpTools::SZRSFtpTools(QObject* parent):
    QObject(parent)
{
    m_sftp = new SecureFileUploader(this);
    connect(m_sftp,&SecureFileUploader::sigDownLoadFinished,this,&SZRSFtpTools::DownloadFinished);
    connect(m_sftp,&SecureFileUploader::sigUpLoadFinished,this,&SZRSFtpTools::UploadFinished);
    connect(m_sftp,&SecureFileUploader::loadError,this,&SZRSFtpTools::LoadFiled);
    connect(m_sftp,&SecureFileUploader::connectError,this,&SZRSFtpTools::connectError);
}

SZRSFtpTools::~SZRSFtpTools()
{
    delete m_sftp;
}

void SZRSFtpTools::setSftpInfo(const QString &host, const QString &userName, const QString &pwd)
{
    m_sftp->setInfo(host,userName,pwd);
    m_host = host;
    m_userName = userName;
    m_pwd = pwd;
}

void SZRSFtpTools::downLoadFile(const QString &savePath, const QString &fname)
{
    m_sftp->DownLoad(savePath,fname);
}

void SZRSFtpTools::downLoadFiles(const QString &savePath, const QStringList &fnames)
{
    m_sftp->DownLoadFiles(savePath,fnames);
}

void SZRSFtpTools::uploadFile(const QString &savePath, const QString &fname)
{
    m_sftp->upload(savePath,fname);
}




  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
Qt是一个跨平台的应用程序开发框架,可以用于开发各种类型的应用程序。Qt提供了QNetworkAccessManager类用于实现网络通信功能,包括上传下载文件。 在Qt实现SFTP上传下载功能,可以使用libssh2库进行操作。libssh2是一个用于实现SSH2协议的C语言库,可以对远程服务器进行认证、上传下载文件等操作。 首先,需要在Qt项目中引入libssh2库。可以通过在.pro文件中添加LIBS += -lssh2指令来链接libssh2库。 接下来,可以创建一个SftpClient类来实现SFTP上传下载功能。在该类中,可以使用libssh2提供的API函数来连接远程SFTP服务器、进行认证、上传下载文件上传文件的步骤如下: 1. 使用libssh2_session_init函数初始化SSH2会话。 2. 使用libssh2_session_startup函数启动SSH2会话。 3. 使用libssh2_userauth_password函数使用用户名和密码进行认证。 4. 使用libssh2_scp_send64函数实现SFTP上传文件下载文件的步骤如下: 1. 使用libssh2_session_init函数初始化SSH2会话。 2. 使用libssh2_session_startup函数启动SSH2会话。 3. 使用libssh2_userauth_password函数使用用户名和密码进行认证。 4. 使用libssh2_scp_recv2函数实现SFTP下载文件。 在上传下载过程中,可以使用Qt提供的QFile类来读取本地文件和写入本地文件。可以使用libssh2提供的相应函数来读取和写入远程文件。 需要注意的是,在进行SFTP上传下载之前,需要确保本地和远程的文件路径是正确的,并且具有相应的权限。 以上就是使用Qt实现SFTP上传下载的大致思路和步骤。具体的实现细节可以参考Qt和libssh2的官方文档和示例代码。
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值