Partage
  • Partager sur Facebook
  • Partager sur Twitter

[Qt]Se connecter à un serveur FTP

Et puis envoyé un fichier

    20 juin 2007 à 18:38:39

    Bonjour, alors voilà je voudrais me connecté au serveur FTP de Free (ftpperso.free.fr) grâce à Qt.

    Le seul problème c'est que j'ai beau chercher, je me retrouve soit devant beacuoup de code assez dur à comprendre soit, devant un code incomplet. Ce qui est le cas sur la doc de Qt.
    Sur CS, il y a une source, mais un peu longue. Et dans les exemples fourni avec Qt, il y a un Client FTP sauf que je vois que le FTP de trolltech est un ftp public, donc dans la source il n'y a pas d'endroit o il y a "password" et ni "user" d'ailleur...

    J'ai ce code et si quelqu'un pouvait m'aider comment le modifié pour que j'arrive à comprendre...

    void FtpWindow::connectOrDisconnect()
     {
         if (ftp) {
             ftp->abort();
             ftp->deleteLater();
             ftp = 0;
             fileList->setEnabled(false);
             cdToParentButton->setEnabled(false);
             downloadButton->setEnabled(false);
             connectButton->setEnabled(true);
             connectButton->setText(tr("Connect"));
             setCursor(Qt::ArrowCursor);
             return;
         }

         setCursor(Qt::WaitCursor);

         ftp = new QFtp(this);
         connect(ftp, SIGNAL(commandFinished(int, bool)),
                 this, SLOT(ftpCommandFinished(int, bool)));
         connect(ftp, SIGNAL(listInfo(const QUrlInfo &)),
                 this, SLOT(addToList(const QUrlInfo &)));
         connect(ftp, SIGNAL(dataTransferProgress(qint64, qint64)),
                 this, SLOT(updateDataTransferProgress(qint64, qint64)));

         fileList->clear();
         currentPath.clear();
         isDirectory.clear();

         QUrl url(ftpServerLineEdit->text());
         url.setUserName("pseudo");
         url.setPassword("pass");
         if (!url.isValid() || url.scheme().toLower() != QLatin1String("ftp")) {
             ftp->connectToHost(ftpServerLineEdit->text(), 21);
             ftp->login();
         } else {
             ftp->connectToHost(url.host(), url.port(21));

             if (!url.userName().isEmpty())
                 ftp->login(QUrl::fromPercentEncoding(url.userName().toLatin1()), url.password());
             else
                 ftp->login();
             if (!url.path().isEmpty())
                 ftp->cd(url.path());
         }

         fileList->setEnabled(true);
         connectButton->setEnabled(false);
         connectButton->setText(tr("Disconnect"));
         statusLabel->setText(tr("Connecting to FTP server %1...")
                              .arg(ftpServerLineEdit->text()));
     }


    J'ai rajoutez ces 2 lignes :

         url.setUserName("pseudo");
         url.setPassword("pass");


    Donc lorsque je lance le programme, il me dit qu'il est connecté au FTP de free mais... le programme ne liste pas ce qui a sur le ftp.

    Une petite aide merci, je voudrais réussir à me connecter sur le ftp de free. merci d'avance !
    • Partager sur Facebook
    • Partager sur Twitter
      22 juin 2007 à 9:14:13

      Ta méthode connectOrDisconnect() ne gère que la connection/déconnexion donc c'est normal qu'aucune information sur le contenu du FTP soit traitée.
      • Partager sur Facebook
      • Partager sur Twitter
        22 juin 2007 à 12:21:31

        Je ne comprend pas trop, j'ai rajouté cette ligne dans la fonction :

        ftp->list();


        Bon cest que vraiment là , je ne comprend pas trop l'utilisation du FTP avec Qt...
        Donc voilà tout le code entier :


         #include <QtGui>
         #include <QtNetwork>

         #include "ftpwindow.h"

         FtpWindow::FtpWindow(QWidget *parent)
             : QDialog(parent), ftp(0)
         {
             ftpServerLabel = new QLabel(tr("Ftp &server:"));
             ftpServerLineEdit = new QLineEdit("ftpperso.free.fr");
             ftpServerLabel->setBuddy(ftpServerLineEdit);

             statusLabel = new QLabel(tr("Please enter the name of an FTP server."));

             fileList = new QTreeWidget;
             fileList->setEnabled(false);
             fileList->setRootIsDecorated(false);
             fileList->setHeaderLabels(QStringList() << tr("Name") << tr("Size") << tr("Owner") << tr("Group") << tr("Time"));
             fileList->header()->setStretchLastSection(false);

             connectButton = new QPushButton(tr("Connect"));
             connectButton->setDefault(true);

             cdToParentButton = new QPushButton;
             cdToParentButton->setIcon(QPixmap(":/images/cdtoparent.png"));
             cdToParentButton->setEnabled(false);

             downloadButton = new QPushButton(tr("Download"));
             downloadButton->setEnabled(false);

             quitButton = new QPushButton(tr("Quit"));

             buttonBox = new QDialogButtonBox;
             buttonBox->addButton(downloadButton, QDialogButtonBox::ActionRole);
             buttonBox->addButton(quitButton, QDialogButtonBox::RejectRole);

             progressDialog = new QProgressDialog(this);

             connect(fileList, SIGNAL(itemActivated(QTreeWidgetItem *, int)),
                     this, SLOT(processItem(QTreeWidgetItem *, int)));
             connect(fileList, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
                     this, SLOT(enableDownloadButton()));
             connect(progressDialog, SIGNAL(canceled()), this, SLOT(cancelDownload()));
             connect(connectButton, SIGNAL(clicked()), this, SLOT(connectOrDisconnect()));
             connect(cdToParentButton, SIGNAL(clicked()), this, SLOT(cdToParent()));
             connect(downloadButton, SIGNAL(clicked()), this, SLOT(downloadFile()));
             connect(quitButton, SIGNAL(clicked()), this, SLOT(close()));

             QHBoxLayout *topLayout = new QHBoxLayout;
             topLayout->addWidget(ftpServerLabel);
             topLayout->addWidget(ftpServerLineEdit);
             topLayout->addWidget(cdToParentButton);
             topLayout->addWidget(connectButton);

             QVBoxLayout *mainLayout = new QVBoxLayout;
             mainLayout->addLayout(topLayout);
             mainLayout->addWidget(fileList);
             mainLayout->addWidget(statusLabel);
             mainLayout->addWidget(buttonBox);
             setLayout(mainLayout);

             setWindowTitle(tr("FTP"));
         }

         QSize FtpWindow::sizeHint() const
         {
             return QSize(500, 300);
         }

         void FtpWindow::connectOrDisconnect()
         {
             if (ftp) {
                 ftp->abort();
                 ftp->deleteLater();
                 ftp = 0;
                 fileList->setEnabled(false);
                 cdToParentButton->setEnabled(false);
                 downloadButton->setEnabled(false);
                 connectButton->setEnabled(true);
                 connectButton->setText(tr("Connect"));
                 setCursor(Qt::ArrowCursor);
                 return;
             }

             setCursor(Qt::WaitCursor);

             ftp = new QFtp(this);
             connect(ftp, SIGNAL(commandFinished(int, bool)),
                     this, SLOT(ftpCommandFinished(int, bool)));
             connect(ftp, SIGNAL(listInfo(const QUrlInfo &)),
                     this, SLOT(addToList(const QUrlInfo &)));
             connect(ftp, SIGNAL(dataTransferProgress(qint64, qint64)),
                     this, SLOT(updateDataTransferProgress(qint64, qint64)));

             fileList->clear();
             currentPath.clear();
             isDirectory.clear();

             QUrl url(ftpServerLineEdit->text());
             url.setUserName("conficiuskyn");
             url.setPassword("ebx182");
             if (!url.isValid() || url.scheme().toLower() != QLatin1String("ftp")) {
                 ftp->connectToHost(ftpServerLineEdit->text(), 21);
                 ftp->login();
             } else {
                 ftp->connectToHost(url.host(), url.port(21));

                 if (!url.userName().isEmpty())
                     ftp->login(QUrl::fromPercentEncoding(url.userName().toLatin1()), url.password());
                 else
                     ftp->login();
                 if (!url.path().isEmpty())
                     ftp->cd(url.path());
             }

             fileList->setEnabled(true);
             connectButton->setEnabled(false);
             connectButton->setText(tr("Disconnect"));
             statusLabel->setText(tr("Connecting to FTP server %1...")
                                  .arg(ftpServerLineEdit->text()));
                                  ftp->list();
         }

         void FtpWindow::downloadFile()
         {
             QString fileName = fileList->currentItem()->text(0);

             if (QFile::exists(fileName)) {
                 QMessageBox::information(this, tr("FTP"),
                                          tr("There already exists a file called %1 in "
                                             "the current directory.")
                                          .arg(fileName));
                 return;
             }

             file = new QFile(fileName);
             if (!file->open(QIODevice::WriteOnly)) {
                 QMessageBox::information(this, tr("FTP"),
                                          tr("Unable to save the file %1: %2.")
                                          .arg(fileName).arg(file->errorString()));
                 delete file;
                 return;
             }

             ftp->get(fileList->currentItem()->text(0), file);

             progressDialog->setLabelText(tr("Downloading %1...").arg(fileName));
             downloadButton->setEnabled(false);
             progressDialog->exec();
         }

         void FtpWindow::cancelDownload()
         {
             ftp->abort();
         }

         void FtpWindow::ftpCommandFinished(int, bool error)
         {
             setCursor(Qt::ArrowCursor);

             if (ftp->currentCommand() == QFtp::ConnectToHost) {
                 if (error) {
                     QMessageBox::information(this, tr("FTP"),
                                              tr("Unable to connect to the FTP server "
                                                 "at %1. Please check that the host "
                                                 "name is correct.")
                                              .arg(ftpServerLineEdit->text()));
                     connectOrDisconnect();
                     return;
                 }

                 statusLabel->setText(tr("Logged onto %1.")
                                      .arg(ftpServerLineEdit->text()));
                 fileList->setFocus();
                 downloadButton->setDefault(true);
                 connectButton->setEnabled(true);
                 return;
             }

             if (ftp->currentCommand() == QFtp::Login)
                 ftp->list();

             if (ftp->currentCommand() == QFtp::Get) {
                 if (error) {
                     statusLabel->setText(tr("Canceled download of %1.")
                                          .arg(file->fileName()));
                     file->close();
                     file->remove();
                 } else {
                     statusLabel->setText(tr("Downloaded %1 to current directory.")
                                          .arg(file->fileName()));
                     file->close();
                 }
                 delete file;
                 enableDownloadButton();
                 progressDialog->hide();
             } else if (ftp->currentCommand() == QFtp::List) {
                 if (isDirectory.isEmpty()) {
                     fileList->addTopLevelItem(new QTreeWidgetItem(QStringList() << tr("<empty>")));
                     fileList->setEnabled(false);
                 }
             }
         }

         void FtpWindow::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() ? ":/images/dir.png" : ":/images/file.png");
             item->setIcon(0, pixmap);

             isDirectory[urlInfo.name()] = urlInfo.isDir();
             fileList->addTopLevelItem(item);
             if (!fileList->currentItem()) {
                 fileList->setCurrentItem(fileList->topLevelItem(0));
                 fileList->setEnabled(true);
             }
         }

         void FtpWindow::processItem(QTreeWidgetItem *item, int /*column*/)
         {
             QString name = item->text(0);
             if (isDirectory.value(name)) {
                 fileList->clear();
                 isDirectory.clear();
                 currentPath += "/" + name;
                 ftp->cd(name);
                 ftp->list();
                 cdToParentButton->setEnabled(true);
                 setCursor(Qt::WaitCursor);
                 return;
             }
         }

         void FtpWindow::cdToParent()
         {
             setCursor(Qt::WaitCursor);
             fileList->clear();
             isDirectory.clear();
             currentPath = currentPath.left(currentPath.lastIndexOf('/'));
             if (currentPath.isEmpty()) {
                 cdToParentButton->setEnabled(false);
                 ftp->cd("/");
             } else {
                 ftp->cd(currentPath);
             }
             ftp->list();
         }

         void FtpWindow::updateDataTransferProgress(qint64 readBytes,
                                                    qint64 totalBytes)
         {
             progressDialog->setMaximum(totalBytes);
             progressDialog->setValue(readBytes);
         }

         void FtpWindow::enableDownloadButton()
         {
             QTreeWidgetItem *current = fileList->currentItem();
             if (current) {
                 QString currentFile = current->text(0);
                 downloadButton->setEnabled(!isDirectory.value(currentFile));
             } else {
                 downloadButton->setEnabled(false);
             }
         }


        Merci d'avance.
        • Partager sur Facebook
        • Partager sur Twitter
          22 juin 2007 à 14:47:01

          faut apprendre à lire aussi :

          Citation : doc

          The listInfo() signal is emitted for each directory entry found.
          The function does not block and returns immediately. The command is scheduled, and its execution is performed asynchronously.

          • Partager sur Facebook
          • Partager sur Twitter
            22 juin 2007 à 18:57:56

            Bon, c'est bizarre... mais même si j'entre de faux identifiants, l'application m'affiche que je suis connecté...
            • Partager sur Facebook
            • Partager sur Twitter

            [Qt]Se connecter à un serveur FTP

            × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
            × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
            • Editeur
            • Markdown