FTP

这里写图片描述

#include "widget2.h"
#include "ui_widget2.h"

#include <QDebug>
#include <QFileInfo>
#include <QFileDialog>
#include <QDir>
#include <QMessageBox>


#pragma execution_character_set("utf-8")

Widget2::Widget2(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget2)
{
    ui->setupUi(this);

    // combox设置为当前应用程序所在目录
    ui->comboBox->addItem(QDir::currentPath());

    connect( ui->fileList, SIGNAL(itemClicked(QTreeWidgetItem*, int)),       this, SLOT(enableDownloadButton(QTreeWidgetItem*, int)) );
    connect( ui->fileList, SIGNAL(itemDoubleClicked(QTreeWidgetItem*, int)), this, SLOT(processItem(QTreeWidgetItem*, int)) );
//    connect( ui->fileList, SIGNAL(itemActivated(QTreeWidgetItem*, int)),   this, SLOT(processItem(QTreeWidgetItem*, int)) );

}

Widget2::~Widget2()
{
    delete ui;
}



// 连接按钮槽
void Widget2::on_connectButton_clicked()
{
    // 清空列表 和 名称是否是目录记录表 和当前路径
    ui->fileList->clear();
    isDirectory.clear();
    currentPath.clear();

    // 每次都必须重新建立ftp连接
    ftp = new QFtp(this);
    connect( ftp, SIGNAL(commandStarted(int)),                  this, SLOT(ftpCommandStarted(int)) );
    connect( ftp, SIGNAL(commandFinished(int, bool)),           this, SLOT(ftpCommandFinished(int, bool)) );
    connect( ftp, SIGNAL(listInfo(QUrlInfo)),                   this, SLOT(addToList(QUrlInfo)));
    connect( ftp, SIGNAL(dataTransferProgress(qint64, qint64)), this, SLOT(updateDataTransferProgress(qint64, qint64)) );

    QString ftpServer = ui->ftpServerLineEdit->text();
    QString userName = ui->userNameLineEdit->text();
    QString passWord = ui->passWordLineEdit->text();

    // 连接并且登录
    ftp->connectToHost(ftpServer);
    ftp->login(userName, passWord);

}

// 返回上级目录按钮槽
void Widget2::on_cdToParentButton_clicked()
{
    // 清空列表 和 名称是否是目录记录表
    ui->fileList->clear();
    isDirectory.clear();

    // 当前路径
    currentPath = currentPath.left(currentPath.lastIndexOf('/'));
    qDebug() << "currentPath: " << currentPath;

    if (currentPath.isEmpty())
    {
        ftp->cd("/");

        ui->cdToParentButton->setEnabled(false);
    }
    else
    {
        ftp->cd(currentPath);
    }

    ftp->list();
}

// 选定指定下载目录按钮槽
void Widget2::on_browserButton_clicked()
{
    QString directory = QFileDialog::getExistingDirectory( this, tr("Choose Directory"), QDir::currentPath() );
    qDebug() << "directory: " << directory;

    if (!directory.isEmpty())
    {
        if (ui->comboBox->findText(directory) == -1)
            ui->comboBox->addItem(directory);
        ui->comboBox->setCurrentIndex(ui->comboBox->findText(directory));
    }

}

// 下载按钮槽
void Widget2::on_downloadButton_clicked()
{
    // 只有在列表当前选中,==>
    if( ui->fileList->currentItem() != NULL )
    {
        QString fileName = ui->fileList->currentItem()->text(0);

        // <==并且选中列表名是一个文件的情况下,才能下载(可以采取更好的方法:禁用)
        if( !isDirectory.value(fileName) )
        {
            //    ftp->get(fileName); //down to where?

            //设置当前目录为下拉菜单的目录
            QString path = ui->comboBox->currentText();
            QDir::setCurrent(path);
            qDebug() << "QDir::currentPath()" << QDir::currentPath();

            //若文件已经存在,弹出提示框
            if (QFile::exists(fileName))
            {
                QMessageBox::information(this,
                                         tr("FTP"),
                                         tr("There already exists a file called %1 in the current directory.").arg(fileName));
                //若已下载,点击OK直接退回主界面
                return;
            }

            file = new QFile(fileName);
            if ( !file->open(QIODevice::WriteOnly) ) {
                delete file;
                return;
            }
            ftp->get(fileName, file);

            // 开始下载时,下载按钮禁用
            ui->downloadButton->setEnabled(false);

            ui->cancelButton->setEnabled(true);

                QFileInfo fileInfo = QFileInfo(fileName);
//                QFileInfo fileInfo2 = QFileInfo(*file);

                qDebug() << fileInfo.absolutePath() << fileInfo.absoluteFilePath();
            //    qDebug() << fileInfo2.absolutePath() << fileInfo2.absoluteFilePath();
        }
    }
}

// 取消按钮槽
void Widget2::on_cancelButton_clicked()
{
    ftp->abort();
}

void Widget2::ftpCommandStarted(int command)
{
//    qDebug() << "command number: " << command;

    int currentCommand = ftp->currentCommand();
    qDebug() << "currentCommand id: " << currentCommand;

    switch (currentCommand)
    {
    case QFtp::ConnectToHost :
        ui->label->setText(tr("正在连接到服务器…"));
        qDebug() << "正在连接到服务器…";
        break;
    case QFtp::Login :
        ui->label->setText(tr("正在登录…"));
        qDebug() << "正在登录…";
        break;
    case QFtp::Get :
        ui->label->setText(tr("正在下载…"));
        qDebug() << "正在下载…";
        break;
    case QFtp::List :
        ui->label->setText(tr("正在生成目录…"));
        qDebug() << "正在生成目录…";
        break;
    case QFtp::Close :
        ui->label->setText(tr("正在关闭连接…"));
        qDebug() << "正在关闭连接…";
    }
}

void Widget2::ftpCommandFinished(int, bool error)
{
    int currentCommand = ftp->currentCommand();
//    qDebug() << "currentCommand id: " << currentCommand;

    if(currentCommand == QFtp::ConnectToHost)
    {
        if(error)
            ui->label->setText(tr("连接服务器出现错误:%1").arg(ftp->errorString()));
        else
            ui->label->setText(tr("连接到服务器成功"));
    }
    else if (currentCommand == QFtp::Login)
    {
        if(error)
            ui->label->setText(tr("登录出现错误:%1").arg(ftp->errorString()));
        else
        {
            ui->label->setText(tr("登录成功"));

            // 登录成功后列表显示
            ftp->list();// attention
        }
    }
    else if (currentCommand == QFtp::Get)
    {
        if(error)
        {
            ui->label->setText(tr("下载出现错误:%1").arg(ftp->errorString()));

            file->close();
            file->remove();

        }
        else
        {
            ui->label->setText(tr("已经完成下载"));

            file->close();// attention
        }

        // 开始完毕时,下载按钮启用
        ui->downloadButton->setEnabled(true); // attention
    }
    else if (currentCommand == QFtp::List)
    {
        qDebug() << "QFtp::List";

        if(error)
            ui->label->setText(tr("生成目录出现错误:%1").arg(ftp->errorString()));
        else
        {
            ui->label->setText(tr("已经完成生成目录"));
        }

        // 如果ftp没有任何内容,向treeWidget中 插入一行空数据
        if (isDirectory.isEmpty())
        {
            qDebug() << "isDirectory.isEmpty(): " << isDirectory.isEmpty();

            ui->fileList->addTopLevelItem( new QTreeWidgetItem(QStringList()<< tr("<empty>")) );
            ui->fileList->setEnabled(false);

            ui->label->setText(tr("该目录为空"));
        }
    }
    else if (currentCommand == QFtp::Close)
    {
        ui->label->setText(tr("已经关闭连接"));
    }
}

void Widget2::addToList(const QUrlInfo &urlInfo)
{
    QTreeWidgetItem *item = new QTreeWidgetItem;
    item->setText(0, urlInfo.name());
    item->setText(1, QString::number(urlInfo.size()));
    item->setText(2, urlInfo.owner());
    item->setText(3, urlInfo.group());
    item->setText(4, urlInfo.lastModified().toString("MMM dd yyyy"));
//    QPixmap pixmap(urlInfo.isDir() ? "../dir.png" : "../file.png");
    QPixmap pixmap(urlInfo.isDir() ? "D:/workspace/MyFtp/dir.png" : "D:/workspace/MyFtp/file.png");
    item->setIcon(0, pixmap);

    // 保存一个路径是否为目录
    isDirectory[urlInfo.name()] = urlInfo.isDir();

    // 向treewidget插入一行信息
    ui->fileList->addTopLevelItem(item);
//    if ( !ui->fileList->currentItem() )
//    {
//        ui->fileList->setCurrentItem(ui->fileList->topLevelItem(0));
//        ui->fileList->setEnabled(true);
//    }
}

void Widget2::enableDownloadButton(QTreeWidgetItem *item, int)
{
    qDebug() << "enableDownloadButton";

    QString name = item->text(0);
    if ( !isDirectory.value(name) )
    {
        ui->downloadButton->setEnabled(true);
    }
    else
    {
        ui->downloadButton->setEnabled(false);
    }

}

void Widget2::processItem(QTreeWidgetItem *item, int)
{
    qDebug() << "processItem";

    QString name = item->text(0);

    // 如果这个文件是个目录,则打开
    if ( isDirectory.value(name) )
    {
        // 清空列表 和 名称是否是目录记录表
        ui->fileList->clear();
        isDirectory.clear();

        // 保存当前路径
        currentPath += "/";
        currentPath += name;
        qDebug() << "currentPath: " << currentPath;

        ftp->cd(name);

        ftp->list();

        ui->cdToParentButton->setEnabled(true);

        // 并且下载按钮禁用
        ui->downloadButton->setEnabled(false);
    }
    else
    {
        ui->downloadButton->setEnabled(true);
    }
}

void Widget2::updateDataTransferProgress(qint64 readBytes, qint64 totalBytes)
{
    qDebug() << "readBytes: " << readBytes << "totalBytes: " <<totalBytes;
    ui->progressBar->setMaximum(totalBytes);
    ui->progressBar->setValue(readBytes);
}




void Widget2::on_browserButton_2_clicked()
{
//    QString fileName = QFileDialog::getOpenFileName();
//    QString fileName = QFileDialog::getOpenFileName(this);
//    QString fileName = QFileDialog::getOpenFileName( this, tr("upload file"), "*", tr("Choose a directory to upload file(*.all files)") );
    uploadFileName  = QFileDialog::getOpenFileName( this, tr("upload file"), "*", tr("Choose a file to upload(*.all files)") );
    qDebug() << "uploadFileName: " << uploadFileName;

    if (!uploadFileName.isEmpty())
    {
        if (ui->comboBox_2->findText(uploadFileName) == -1)
            ui->comboBox_2->addItem(uploadFileName);
        ui->comboBox_2->setCurrentIndex(ui->comboBox_2->findText(uploadFileName));
    }
}

void Widget2::on_uploadButton_clicked()
{
    QDir::setCurrent(currentPath);
    qDebug() << "QDir::currentPath()" << QDir::currentPath();

    uploadFile = new QFile(uploadFileName);
    if (!uploadFile->open(QIODevice::ReadOnly)) {
        delete file;
        return;
    }
    ftp->put(uploadFile, uploadFileName);

}

void Widget2::on_cancelButton_2_clicked()
{

}

ftp源码资源下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值