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: [email protected]
**
** 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 

#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: [email protected]
**
** 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 
#include 

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:"<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 
#include 



#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 


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);
}




你可能感兴趣的:(QT5,qt,开发语言)