How to upload with progress bar using pyside qftp?

Asked

Viewed 226 times

2

How can I upload using pyside qftp? I already have a client ftp program that downloads. Below follows my ftp client code.

#!/usr/bin/env python
# -*- coding: latin-1 -*-

import os, sys
import sip
sip.setapi('QString', 2)

from PySide import QtCore, QtGui, QtNetwork

import ftp_rc

__version__ = '0.1'

class FtpWindow(QtGui.QDialog):
    def __init__(self, parent=None):
        super(FtpWindow, self).__init__(parent)

        self.isDirectory = {}
        self.currentPath = ''
        self.ftp = None
        self.outFile = None
        self.outUpFile = None

        ftpLoginLabel = QtGui.QLabel('&Usuário:')
        ftpPasswdLabel = QtGui.QLabel('&Senha:')
        ftpServerLabel = QtGui.QLabel("&Ftp server:")
        self.ftpLoginLineEdit = QtGui.QLineEdit('usuario')
        self.ftpLoginLineEdit.selectAll()
        self.ftpPasswdLineEdit = QtGui.QLineEdit('******')
        self.ftpPasswdLineEdit.selectAll()
        self.ftpPasswdLineEdit.setEchoMode(QtGui.QLineEdit.Password)
        self.ftpServerLineEdit = QtGui.QLineEdit('ftp.trolltech.com')
        ftpLoginLabel.setBuddy(self.ftpLoginLineEdit)
        ftpServerLabel.setBuddy(self.ftpServerLineEdit)
        ftpPasswdLabel.setBuddy(self.ftpPasswdLineEdit)

        self.statusLabel = QtGui.QLabel("Por favor entre com o USUÀRIO e SENHA e o SERVIDOR FTP")

        self.fileList = QtGui.QTreeWidget()
        self.fileList.setEnabled(False)
        self.fileList.setRootIsDecorated(False)
        self.fileList.setHeaderLabels(("Nome", "Tamanho", "Propriétario", "Grupo", "Ultima Modificação"))
        self.fileList.header().setStretchLastSection(False)

        self.connectButton = QtGui.QPushButton("Connect")
        self.connectButton.setDefault(True)

        self.cdToParentButton = QtGui.QPushButton()
        self.cdToParentButton.setIcon(QtGui.QIcon(':/images/cdtoparent.png'))
        self.cdToParentButton.setEnabled(False)

        self.mkdirToParentButton = QtGui.QPushButton()
        self.mkdirToParentButton.setIcon(QtGui.QIcon(':/images/newFolder.png'))
        self.mkdirToParentButton.setEnabled(False)


        self.uploadButton = QtGui.QPushButton('Upload')
        self.uploadButton.setEnabled(False)

        self.downloadButton = QtGui.QPushButton("Download")
        self.downloadButton.setEnabled(False)

        self.quitButton = QtGui.QPushButton("Quit")

        buttonBox = QtGui.QDialogButtonBox()
        buttonBox.addButton(self.uploadButton,
                            QtGui.QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.downloadButton,
                QtGui.QDialogButtonBox.ActionRole)
        buttonBox.addButton(self.quitButton, QtGui.QDialogButtonBox.RejectRole)

        self.progressDialog = QtGui.QProgressDialog(self)

        self.fileList.itemActivated.connect(self.processItem)
        self.fileList.currentItemChanged.connect(self.enableDownloadButton)
        self.progressDialog.canceled.connect(self.cancelDownload)
        self.connectButton.clicked.connect(self.connectOrDisconnect)
        self.cdToParentButton.clicked.connect(self.cdToParent)
        self.mkdirToParentButton.clicked.connect(self.mkdirToParent)
        self.uploadButton.clicked.connect(self.uploadFile)
        self.downloadButton.clicked.connect(self.downloadFile)
        self.quitButton.clicked.connect(self.close)

        topLayout = QtGui.QHBoxLayout()
        topLayout.addWidget(ftpLoginLabel)
        topLayout.addWidget(self.ftpLoginLineEdit)
        topLayout.addWidget(ftpPasswdLabel)
        topLayout.addWidget(self.ftpPasswdLineEdit)
        topLayout.addWidget(ftpServerLabel)
        topLayout.addWidget(self.ftpServerLineEdit)
        topLayout.addWidget(self.cdToParentButton)
        topLayout.addWidget(self.mkdirToParentButton)
        topLayout.addWidget(self.connectButton)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(topLayout)
        mainLayout.addWidget(self.fileList)
        mainLayout.addWidget(self.statusLabel)
        mainLayout.addWidget(buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle("CLIENTE FTP")
        self.setWindowIcon(QtGui.QIcon(':/images/janela.png'))


    def sizeHint(self):
        return QtCore.QSize(800, 600)

    def connectOrDisconnect(self):
        if self.ftp:
            self.ftp.abort()
            self.ftp.deleteLater()
            self.ftp = None

            self.fileList.setEnabled(False)
            self.cdToParentButton.setEnabled(False)
            self.downloadButton.setEnabled(False)
            self.uploadButton.setEnabled(False)
            self.connectButton.setEnabled(True)
            self.connectButton.setText("Connect")
            self.setCursor(QtCore.Qt.ArrowCursor)

            return

        self.setCursor(QtCore.Qt.WaitCursor)

        self.ftp = QtNetwork.QFtp(self)
        self.ftp.commandFinished.connect(self.ftpCommandFinished)
        self.ftp.listInfo.connect(self.addToList)
        self.ftp.dataTransferProgress.connect(self.updateDataTransferProgress)

        self.fileList.clear()
        self.currentPath = ''
        self.isDirectory.clear()

        url = QtCore.QUrl(self.ftpServerLineEdit.text())
        if not url.isValid() or url.scheme().lower() != 'ftp':
            self.ftp.connectToHost(self.ftpServerLineEdit.text(), 21)
            self.ftp.login(user=self.ftpLoginLineEdit.text(), password=self.ftpPasswdLineEdit.text())
        else:
            self.ftp.connectToHost(url.host(), url.port(21))

            user_name = url.userName()
            if user_name:
                try:
                    # Python v3.
                    user_name = bytes(user_name, encoding='latin1')
                except:
                    # Python v2.
                    pass

                self.ftp.login(QtCore.QUrl.fromPercentEncoding(user_name), url.password())
            else:
                self.ftp.login()

            if url.path():
                self.ftp.cd(url.path())

        self.fileList.setEnabled(True)
        self.uploadButton.setEnabled(True)
        self.mkdirToParentButton.setEnabled(True)
        self.connectButton.setEnabled(False)
        self.connectButton.setText("Disconnect")
        self.statusLabel.setText("Conectando ao serveidor FTP %s..." % self.ftpServerLineEdit.text())

    def uploadFile(self):

        filename = QtGui.QFileDialog.getOpenFileName(self, 'Upload File', '.')
        data = QtCore.QFile(filename[0])
        #QtCore.QFile(QtCore.QIODevice.openMode(1))
        data.open(QtCore.QFile.ReadOnly)
        #qdata = QtCore.QBitArray()
        qdata = QtCore.QByteArray(data.readAll())
        file = os.path.basename(filename[0])
        print data
        if not self.fileList.currentItem():
            self.ftp.put(qdata, file, self.ftp.TransferType())
        elif "." in self.fileList.currentItem().text(0):
            self.ftp.put(qdata, self.fileList.currentItem().parent().text(0) + file)
        elif self.fileList.currentItem().text(0) == "/":
            self.ftp.put(qdata, file)
            self.progressDialog.setLabelText("uploading %s..." % fileName)
            #self.downloadButton.setEnabled(False)
            self.progressDialog.exec_()
        else:
            print "erro"

    def downloadFile(self):
        fileName = self.fileList.currentItem().text(0)
        fn = QtGui.QFileDialog.getSaveFileName(self, "Salvar como...", None,
                                               "Todos os arquivos (*.*)")

        if not fn:
            return False

        if QtCore.QFile.exists(fn):
            QtGui.QMessageBox.information(self, "CLIENTE FTP",
                    "Ja existe uma arquivo chamado %s no diretorio "
                    "corrente." % fileName)
            return

        self.outFile = QtCore.QFile(fn)
        if not self.outFile.open(QtCore.QIODevice.WriteOnly):
            QtGui.QMessageBox.information(self, "CLIENTE FTP",
                    "Unable to save the file %s: %s." % (fileName, self.outFile.errorString()))
            self.outFile = None
            return

        self.ftp.get(self.fileList.currentItem().text(0), self.outFile)

        self.progressDialog.setLabelText("Downloading %s..." % fileName)
        self.downloadButton.setEnabled(False)
        self.progressDialog.exec_()

    def cancelDownload(self):
        self.ftp.abort()

    def ftpCommandFinished(self, _, error):
        self.setCursor(QtCore.Qt.ArrowCursor)

        if self.ftp.currentCommand() == QtNetwork.QFtp.ConnectToHost:
            if error:
                QtGui.QMessageBox.information(self, "CLIENTE FTP",
                        "Nao foi possivel se conectar ao servidor ftp %s. Por favor "
                        "verifique se o nome do host esta correto." % self.ftpServerLineEdit.text())
                self.connectOrDisconnect()
                return

            self.statusLabel.setText("Conectado como %s em %s." % (self.ftpLoginLineEdit.text(),self.ftpServerLineEdit.text()))
            self.fileList.setFocus()
            self.downloadButton.setDefault(True)
            self.connectButton.setEnabled(True)
            return

        if self.ftp.currentCommand() == QtNetwork.QFtp.Login:
            self.ftp.list()

        if self.ftp.currentCommand() == QtNetwork.QFtp.Put:
            if error:
                self.statusLabel.setText('upload cancelado do %s.' % self)

        if self.ftp.currentCommand() == QtNetwork.QFtp.Get:
            if error:
                self.statusLabel.setText("download cancelado do %s." % self.outFile.fileName())
                self.outFile.close()
                self.outFile.remove()
            else:
                self.statusLabel.setText("Downloaded %s para o diretorio." % self.outFile.fileName())
                self.outFile.close()

            self.outFile = None
            self.enableDownloadButton()
            self.progressDialog.hide()
        elif self.ftp.currentCommand() == QtNetwork.QFtp.List:
            if not self.isDirectory:
                self.fileList.addTopLevelItem(QtGui.QTreeWidgetItem(["<empty>"]))
                self.fileList.setEnabled(False)

    def addToList(self, urlInfo):
        item = QtGui.QTreeWidgetItem()
        item.setText(0, urlInfo.name())
        item.setText(1, str(urlInfo.size()))
        item.setText(2, urlInfo.owner())
        item.setText(3, urlInfo.group())
        item.setText(4, urlInfo.lastModified().toString('dd MMM yyyy HH:MM'))

        if urlInfo.isDir():
            icon = QtGui.QIcon(':/images/dir.png')
        else:
            icon = QtGui.QIcon(':/images/file.png')
        item.setIcon(0, icon)

        self.isDirectory[urlInfo.name()] = urlInfo.isDir()
        self.fileList.addTopLevelItem(item)
        if not self.fileList.currentItem():
            self.fileList.setCurrentItem(self.fileList.topLevelItem(0))
            self.fileList.setEnabled(True)

    def processItem(self, item):
        name = item.text(0)
        if self.isDirectory.get(name):
            self.fileList.clear()
            self.isDirectory.clear()
            self.currentPath += '/' + name
            self.ftp.cd(name)
            self.ftp.list()
            self.cdToParentButton.setEnabled(True)
            self.setCursor(QtCore.Qt.WaitCursor)

    def cdToParent(self):
        self.setCursor(QtCore.Qt.WaitCursor)
        self.fileList.clear()
        self.isDirectory.clear()

        dirs = self.currentPath.split('/')
        if len(dirs) > 1:
            self.currentPath = ''
            #self.cdToParentButton.setEnabled(False)
            self.ftp.cd('..')
        else:
            self.currentPath = '/'.join(dirs[:-1])
            self.ftp.cd(self.currentPath)

        self.ftp.list()

    def mkdirToParent(self):
        foldername = unicode(self.commandEdit.text())

    def updateDataTransferProgress(self, readBytes, totalBytes):
        self.progressDialog.setMaximum(totalBytes)
        self.progressDialog.setValue(readBytes)

    def enableDownloadButton(self):
        current = self.fileList.currentItem()
        if current:
            currentFile = current.text(0)
            self.downloadButton.setEnabled(not self.isDirectory.get(currentFile))
        else:
            self.downloadButton.setEnabled(False)


if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    ftpWin = FtpWindow()
    ftpWin.show()
    sys.exit(ftpWin.exec_())

In the code above you have an attempt of mine to upload but I was not successful.

  • 1

    Which error did you get? Where is your attempt located? Try to put more detail into understanding the problem and explain how you tried to solve it. It will help people understand better :)

  • 1

    Please put the entire code into one gist or in a repository github and put here only the relevant part of the question. It will be easier for someone to support you.

  • 1

    Could you simplify the code to show only the relevant section? (i.e. take out the whole part of Qt, etc., so that it is simple for those who answer to reproduce their problem) The ideal would be to put the smallest possible program that still demonstrates the problem you are having.

  • Good afternoon staff actually what I’m needing is an example of how to upload files using the function put library qftp i researched on the internet but could not find examples that explain how to use this function!

1 answer

2


In the pyside you have a method called Qprogressbar, he does exactly what you need.

self.client = QtNetwork.QFtp()
self.connect(self.client, QtCore.SIGNAL('stateChanged(int)'), self.updateStatus)
self.connect(self.client, QtCore.SIGNAL('dataTransferProgress(int,int)'), self.updateProgress)
self.client.connectToHost('ftp.avelino.xxx')
self.client.login("ting","moomin")

def updateProgress(self, position, total):
    print(str(position) + "::" + str(total))

The method updateProgress returns exactly what you need, where this/total.

reference: http://srinikom.github.io/pyside-docs/PySide/QtGui/QProgressBar.html

  • Thank you very much, the more you could tbm give me example of how to upload using Qftp of Pyside?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.