QT QFtp使用实例 从FTP下载一个文件

1. ftp://ftp.denx.de/pub/u-boot/lowboot-1.0.0.patch.gz  下载文件

FtpGet.h

#ifndef FTPGET_H
#define FTPGET_H

#include <QUrl>
#include <QFtp>
#include <QFile>

class Ftpget : public QObject
{
    Q_OBJECT
public:
    Ftpget(QObject *parent=0);
    bool getFile(const QUrl &url);

signals:
    void done();

private slots:
    void ftpDone(bool error);

private:
    QFtp ftp;
    QFile file;
};

#endif // FTPGET_H
FtpGet.cpp

#include "FtpGet.h"
#include <iostream>
#include <QFileInfo>

Ftpget::Ftpget(QObject *parent)
    :QObject(parent)
{
    connect(&ftp, SIGNAL(done(bool)), this, SLOT(ftpDone(bool)));
}

bool Ftpget::getFile(const QUrl &url)
{
    if( !url.isValid() )
    {
        std::cerr << "Error: Invaild URL" << std::endl;
        return false;
    }
    if( url.scheme() != "ftp" )
    {
        std::cerr << "Error: URL must start with 'ftp'" << std::endl;
        return false;
    }
    if( url.path().isEmpty() )
    {
        std::cerr << "Error: URL has no path " << std::endl;
        return false;
    }

    QString localFileName = QFileInfo(url.path()).fileName();
    if( localFileName.isEmpty() )
        localFileName = "ftpget.out";

    file.setFileName(localFileName);
    if( !file.open(QIODevice::WriteOnly) )
    {
        std::cerr << "Error: cannot write file"
             << qPrintable(file.fileName()) << ":"
             << qPrintable(file.errorString()) << std::endl;
        return false;
    }

    ftp.connectToHost(url.host(), url.port(21));
    ftp.login();
    ftp.get(url.path(), &file);
    ftp.close();
    return true;
}

void Ftpget::ftpDone(bool error)
{
    if( error )
        std::cerr << "Error: " << qPrintable(ftp.errorString()) << std::endl;
    else
        std::cerr << "File downloaded as " << qPrintable(file.fileName()) << std::endl;
    file.close();
    emit done();
}
main.cpp
#include <QtGui/QApplication>
#include <QCoreApplication>
#include <QStringList>
#include <iostream>
#include "FtpGet.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QStringList args = QCoreApplication::arguments();
    if( args.count() != 2 )
    {
        std::cerr << "Ex: ftpget ftp://xxxxx" << std::endl;
        return 1;
    }

    Ftpget getter;
    if( !getter.getFile(QUrl(args[1])) )
        return 1;
    QObject::connect(&getter, SIGNAL(done()), &a, SLOT(quit()));

    return a.exec();
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值