Qt FTP文件上传下载简单例子

发布于:2022-12-29 ⋅ 阅读:(697) ⋅ 点赞:(0)

一、简述

      记--Qt5 默认已经不支持QFtp了,需要自己编译。例子使用QNetworkAccessManager实现简单的ftp文件上传和下载。

      例子打包:外链:https://wwm.lanzouv.com/b0caushud 密码:1puy

二、效果

例子中在虚拟机Ubuntu16.04 搭建了ftp服务器,windwos主机跟Ubuntu虚拟机能ping通。

用户名密码可以使用Ubuntu的账号,也可以自己添加新用户。

三、工程结构

四、源文件 

mainwindow.h文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include<QtNetwork/QNetworkAccessManager>
#include<QtNetwork/QNetworkRequest>
#include<QtNetwork/QNetworkReply>

#define FTP_PORT    21

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void on_pushButtonDownload_clicked();
    void slot_NetworkAccessManagerUploadProcess(QNetworkReply*);
    void slot_NetworkAccessManagerDownloadProcess(QNetworkReply*);

    void on_pushButtonUploadFile_clicked();

private:
    Ui::MainWindow *ui;
    QNetworkAccessManager mNetworkAccessManagerUpload;
    QNetworkAccessManager mNetworkAccessManagerDownload;
};

#endif // MAINWINDOW_H

main.cpp文件

#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

mainwindow.cpp文件

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>
#include <QFileDialog>
#include <QFile>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(&mNetworkAccessManagerUpload, SIGNAL(finished(QNetworkReply*)), SLOT(slot_NetworkAccessManagerUploadProcess(QNetworkReply*)));
    connect(&mNetworkAccessManagerDownload, SIGNAL(finished(QNetworkReply*)), SLOT(slot_NetworkAccessManagerDownloadProcess(QNetworkReply*)));
    //mNetworkAccessManagerDownload.downloadProgress 进度
}

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

//下载文件
void MainWindow::on_pushButtonDownload_clicked()
{
    QUrl url;
    url.setScheme("ftp");
    url.setHost(ui->lineEditHost->text());
    url.setPort(ui->lineEditPort->text().toInt());
    url.setUserName(ui->lineEditUserName->text());
    url.setPassword(ui->lineEditPwd->text());
    url.setPath(ui->lineEditDownloadUrl->text());
    mNetworkAccessManagerDownload.get((QNetworkRequest(url)));
}

//下载结果处理
void MainWindow::slot_NetworkAccessManagerDownloadProcess(QNetworkReply *reply)
{
    QNetworkReply::NetworkError error = reply->error();
    switch(error){
        case QNetworkReply::NoError:
            {
                QByteArray data = reply->readAll();//大文件可以使用QIODevice或reply->readData()
                QFileInfo fileInfo(ui->lineEditDownloadUrl->text());
                QFile file(fileInfo.fileName());
                if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
                    QMessageBox::critical(this,"错误", "保存失败!");
                } else {
                    //将内容写入文件
                    file.write(data);
                    file.close();
                    QMessageBox::information(this,"提示", "下载成功!已保存到" + file.fileName());
                }
            }
            break;
        case QNetworkReply::HostNotFoundError:
            QMessageBox::critical(this,"错误", "Host Not Found!");
            break;
        case QNetworkReply::AuthenticationRequiredError:
            QMessageBox::critical(this,"错误", "AuthenticationRequiredError!");
            break;
        default:
            QMessageBox::critical(this,"错误", "未知错误! error:" + error);
        break;
    }
}

//上传文件
void MainWindow::on_pushButtonUploadFile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择文件", ".", "文本文件(*.txt)");
    if (fileName.isEmpty()) {
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(this,"错误", "打开文件失败!");
        return;
    }

    QByteArray data = file.readAll();
    file.close();

    QUrl url;
    url.setScheme("ftp");
    url.setHost(ui->lineEditHost->text());
    url.setPort(ui->lineEditPort->text().toInt());
    url.setUserName(ui->lineEditUserName->text());
    url.setPassword(ui->lineEditPwd->text());
    QFileInfo fileInfo(fileName);
    url.setPath(ui->lineEditUploadUrl->text().append("/").append(fileInfo.fileName()));

    mNetworkAccessManagerUpload.put(QNetworkRequest(url), data);
}


//上传结果处理
void MainWindow::slot_NetworkAccessManagerUploadProcess(QNetworkReply *reply)
{
    QNetworkReply::NetworkError error = reply->error();
    switch(error){
        case QNetworkReply::NoError:
            QMessageBox::information(this,"提示", "上传成功!");
            break;
        case QNetworkReply::HostNotFoundError:
            QMessageBox::critical(this,"错误", "Host Not Found!");
            break;
        case QNetworkReply::AuthenticationRequiredError:
            QMessageBox::critical(this,"错误", "Authentication Required Error!");
            break;
        default:
            QMessageBox::critical(this,"错误", "未知错误!");
        break;
    }
}

五、附

例子中在虚拟机Ubuntu16.04 搭建了ftp服务器,windwos主机跟Ubuntu虚拟机能ping通。

5.1 确认能ping通:

5.2 确认ftp服务器已经启动

 5.3 Ubuntu16.04 安装ftp服务器

//在线安装,一般安装成功后ftp服务器就自动启动了,使用ps -ef | grep vsftpd确认
sudo apt-get install vsftpd

//编辑配置文件, 启用write_enable=YES 不然不能上传文件
sudo /etc/vsftpd.conf

修改配置后保存然后重启vsftpd,执行sudo /etc/init.d/vsftpd restart

//如果之前安装过但是有问题,可以使用这一句进行移除
sudo apt-get purge vsftpd

本文含有隐藏内容,请 开通VIP 后查看