Novah
Novah

Reputation: 90

How to create a directory on the FTP server in Qt 5.5

How to create a directory with the help of a QNetworkRequest. I know that it does not have a function like mkDir() that beat in KFtp, but somehow it can is possible through http request, or something different. Thanks in advance.

Upvotes: 1

Views: 3280

Answers (2)

Novah
Novah

Reputation: 90

Well, in short, I decided to problems found on GitHub QtFtp compiled and threw to the right place, and it worked. Here snare to the archive (only in draft qftp remove subproject 'example' and that will not compile).https://codeload.github.com/qtproject/qtftp/zip/master

Upvotes: 1

phyatt
phyatt

Reputation: 19112

You should use QtFtp. It isn't built in anymore as of Qt 5, so you need to build it from the sources and add it to your Qt install. I've done it on Windows and OSX with Qt 5.2. Its not too bad.

I only found online documentation for it under Qt 4.8.

http://doc.qt.io/qt-4.8/qftp.html#details

This is the function you are looking for.

http://doc.qt.io/qt-4.8/qftp.html#mkdir

Add QFtp in Qt 5.0

https://forum.qt.io/topic/45242/solved-how-to-do-an-ftp-client-with-qt5-what-classes-to-use

Examples

Documented Example:

http://doc.qt.io/qt-4.8/qt-network-qftp-example.html

Here is the example I worked with that needed QtFtp access.

Example using QtFtp:

https://github.com/magist3r/QtWeb/blob/fffaddce36a594013f987e469dbf22d94a78dfa9/src/webview.cpp

webview.h

//////////////////////////////////////////////////// AC: FTP implementation
    QFtp*  m_ftp;
    QFile* m_ftpFile;
    QString m_ftpHtml;

    QProgressDialog         *m_ftpProgressDialog;
    QHash<QString, bool>    m_ftpIsDirectory;
    QString                 m_ftpCurrentPath;

private:
    void ftpCheckDisconnect();
    void ftpDownloadFile(const QUrl &url, QString filename );

private slots:
    void ftpCancelDownload();
    void ftpCommandFinished(int commandId, bool error);
    void ftpAddToList(const QUrlInfo &urlInfo);
    void ftpUpdateDataTransferProgress(qint64 readBytes, qint64 totalBytes);

webview.cpp

///////////////////////////////////////////////////////////////
// AC: FTP impl

void WebView::ftpCancelDownload()
{
    if (m_ftp)
        m_ftp->abort();
}


void WebView::ftpCheckDisconnect()
{
    if (m_ftp)
    {
        m_ftp->abort();
        m_ftp->deleteLater();
        m_ftp = NULL;
        setCursor(Qt::ArrowCursor);
    }
}

void WebView::loadFtpUrl(const QUrl &url)
{
    m_is_loading = true;

    m_ftpHtml.clear();
    setCursor(Qt::WaitCursor);

    m_ftp = new QFtp(this);
    connect(m_ftp, SIGNAL(commandFinished(int, bool)),
            this, SLOT(ftpCommandFinished(int, bool)));
    connect(m_ftp, SIGNAL(listInfo(const QUrlInfo &)),
            this, SLOT(ftpAddToList(const QUrlInfo &)));
    connect(m_ftp, SIGNAL(dataTransferProgress(qint64, qint64)),
            this, SLOT(ftpUpdateDataTransferProgress(qint64, qint64)));

    m_ftpHtml.clear();
    m_ftpCurrentPath.clear();
    m_ftpIsDirectory.clear();

    if (!url.isValid() || url.scheme().toLower() != QLatin1String("ftp")) {
        m_ftp->connectToHost(url.toString(), 21);
        m_ftp->login();
    } else {
        m_ftp->connectToHost(url.host(), url.port(21));

        if (!url.userName().isEmpty())
            m_ftp->login(QUrl::fromPercentEncoding(url.userName().toLatin1()), url.password());
        else
            m_ftp->login();
        if (!url.path().isEmpty())
        {
            if (!url.hasQuery())
            {
                m_ftp->cd(url.path());
            }
            else
            {
                // Downloading file
                QString f =  url.path();
                int ind = f.lastIndexOf('/');
                QString dir = "";
                if (ind != -1 )
                {
                    dir = f.left(ind + 1);
                }

                m_ftp->cd(dir);

                setStatusBarText(tr("Downloading file %1...").arg(url.toString()));
                return;
            }
        }
    }

    setStatusBarText(tr("Connecting to FTP server %1...").arg(url.toString()));
}

void WebView::ftpDownloadFile(const QUrl &url, QString fileName )
{
    if (!m_ftp)
        return;

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

    QString downloadDirectory = dirDownloads(true);
    if (!downloadDirectory.isEmpty() && downloadDirectory.right(1) != QDir::separator())
        downloadDirectory += QDir::separator();

    QString fn = QFileDialog::getSaveFileName(this, tr("Save File"), downloadDirectory + fileName);
    if (fn.isEmpty()) 
    {
        QMessageBox::information(this, tr("FTP"), tr("Download canceled."));
        return;
    }


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

    m_ftp->get(fileName, m_ftpFile);

    m_ftpProgressDialog->setLabelText(QString("&nbsp;<br>" + tr("Downloading <b>%1</b>")).arg(fn));
    m_ftpProgressDialog->setWindowTitle(tr("FTP Download"));
    m_ftpProgressDialog->setModal(true);
}


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

    if (!m_ftp)
        return;

    if (m_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(m_initialUrl.toString()));
            ftpCheckDisconnect();
            return;
        }

        setStatusBarText(tr("Logged onto %1.").arg(m_initialUrl.host()));
        return;
    }

    if (m_ftp->currentCommand() == QFtp::Login)
    {
        setStatusBarText(tr("Listing %1...").arg(m_initialUrl.toString()));
        m_ftpHtml.clear();
        QString u = m_initialUrl.toString();
        int ind = u.lastIndexOf('/');
        if (ind != -1 && ind > 7 && ind < u.length() -1 )
        {
            u = u.left(ind);
        }
        else
            u = "";

        if ( !m_initialUrl.hasQuery() )
        {
            //<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">
            m_ftpHtml = "<html><body><PRE><H2>Contents of " + m_initialUrl.toString() + "</H2>" + 
                (u.length() > 0 ? "<p> Go to <a href=\"" + u + "\">parent directory</a>" : QString(""))+
                "<p><table cellpadding=3 cellspacing=3><tr><td></td><td><b>Name</b></td><td width=70 align=right><b>Size</b></td><td width=110 align=center><b>Date/Time</b></td></tr><tr><td>&nbsp;</td><td></td></tr>";
            setCursor(Qt::WaitCursor);
            m_ftp->list();
        }
        else
        {
            QString f =  m_initialUrl.toString().left(m_initialUrl.toString().length() - 4);
            int ind = f.lastIndexOf('/');
            if (ind != -1 )
            {
                f = f.right(f.length() - ind - 1);
            }
            ftpDownloadFile(m_initialUrl, f );
        }
    }

    if (m_ftp->currentCommand() == QFtp::Get) 
    {
        if (error) 
        {
            setStatusBarText(tr("Canceled download of %1").arg(m_ftpFile->fileName()));
            m_ftpFile->close();
            m_ftpFile->remove();
        } 
        else 
        {
            DownloadManager* dm = BrowserApplication::downloadManager();
            setStatusBarText(tr("Successfully downloaded file %1").arg(m_ftpFile->fileName()));
            m_ftpFile->close();

            dm->addItem(m_initialUrl, m_ftpFile->fileName(), true );
        }
        delete m_ftpFile;
        m_ftpProgressDialog->hide();
    } 
    else 
    if (m_ftp->currentCommand() == QFtp::List) 
    {
        setStatusBarText(tr("Listed %1").arg(m_initialUrl.toString()));
        if (m_ftpIsDirectory.isEmpty()) 
        {
            m_ftpHtml += "<tr><td>Directory is empty</td></tr>";
        }
        m_ftpHtml += "</table></PRE></body></html>";
        setHtml(m_ftpHtml, m_initialUrl);
        //page()->mainFrame()->setHtml(m_ftpHtml, m_initialUrl);
        //QString html = page()->mainFrame()->toHtml () ;
        //page()->setViewportSize(size()); 
        m_is_loading = false;

    }

    urlChanged(m_initialUrl);
}


void WebView::ftpAddToList(const QUrlInfo &urlInfo)
{
    m_ftpHtml += "<tr><td>" + (urlInfo.isDir() ? QString("DIR") : QString("")) +  "</td>"; 
    m_ftpHtml += "<td>" + (urlInfo.isDir() ? QString("<b>") : QString("")) + 
        (urlInfo.isDir() ? QString("<a href=\"" + m_initialUrl.toString() + (m_initialUrl.toString().right(1) == "/" ? QString(""): QString("/"))
        + urlInfo.name() + "\">") : QString("")) + 
        urlInfo.name() + (urlInfo.isDir() ? QString("</a>") : QString("")) + "</td>";
    m_ftpHtml += "<td align=right>" + (urlInfo.isDir() ? "" : QString::number(urlInfo.size())) + "</td>";
    m_ftpHtml += "<td align=center>" + urlInfo.lastModified().toString("MMM dd yyyy") + "</td>";
    m_ftpHtml += "<td>" + 
        (!urlInfo.isDir() ? QString("<a href=\"" + m_initialUrl.toString() + (m_initialUrl.toString().right(1) == "/" ? QString(""): QString("/"))
        + urlInfo.name() + "?get\">") : QString("")) + 
        (!urlInfo.isDir() ? QString("GET FILE</a>") : QString("")) + "</td></tr>";

    m_ftpIsDirectory[urlInfo.name()] = urlInfo.isDir();

}

void WebView::ftpUpdateDataTransferProgress(qint64 readBytes,
                                           qint64 totalBytes)
{
    if (m_ftpProgressDialog)
    {
        m_ftpProgressDialog->setMaximum(totalBytes);
        m_ftpProgressDialog->setValue(readBytes);
    }
}

Hope that helps.

Upvotes: 1

Related Questions