使用PyQt5创建一个FTP客户端应用程序。它连接到linux创建的FTP服务器,并提供了上传和下载文件的功能。
时间: 2024-04-11 09:33:49 浏览: 9
可以使用PyQt5和ftplib库创建一个FTP客户端应用程序。以下是一个示例代码,展示了如何连接到Linux上的FTP服务器,并提供上传和下载文件的功能。
```python
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog, QMessageBox
from ftplib import FTP
class FTPClient(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("FTP Client")
self.setGeometry(100, 100, 300, 200)
self.btn_upload = QPushButton("Upload", self)
self.btn_upload.setGeometry(50, 50, 200, 30)
self.btn_upload.clicked.connect(self.uploadFile)
self.btn_download = QPushButton("Download", self)
self.btn_download.setGeometry(50, 100, 200, 30)
self.btn_download.clicked.connect(self.downloadFile)
def uploadFile(self):
file_path, _ = QFileDialog.getOpenFileName(self, 'Select file to upload', '', 'All Files (*)')
if file_path:
ftp = FTP('ftp.example.com') # Replace with your FTP server address
ftp.login('username', 'password') # Replace with your FTP credentials
file_name = file_path.split('/')[-1]
try:
with open(file_path, 'rb') as file:
ftp.storbinary(f'STOR {file_name}', file)
QMessageBox.information(self, 'Success', 'File uploaded successfully!')
except Exception as e:
QMessageBox.critical(self, 'Error', f'Failed to upload file: {str(e)}')
ftp.quit()
def downloadFile(self):
file_name, _ = QFileDialog.getSaveFileName(self, 'Save file', '', 'All Files (*)')
if file_name:
ftp = FTP('ftp.example.com') # Replace with your FTP server address
ftp.login('username', 'password') # Replace with your FTP credentials
try:
with open(file_name, 'wb') as file:
ftp.retrbinary(f'RETR {file_name}', file.write)
QMessageBox.information(self, 'Success', 'File downloaded successfully!')
except Exception as e:
QMessageBox.critical(self, 'Error', f'Failed to download file: {str(e)}')
ftp.quit()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = FTPClient()
window.show()
sys.exit(app.exec_())
```
请注意,上述代码中的服务器地址、用户名、密码等需要替换为您实际的FTP服务器信息。此外,代码中使用的是基本的FTP功能,如果需要更复杂的功能,可以根据ftplib库的文档进行扩展。