QNetworkAccessManager下载文件
时间: 2023-08-15 16:08:54 浏览: 139
好的,您可以通过以下代码来使用QNetworkAccessManager下载文件:
```python
import sys
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QProgressBar
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
class Downloader(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle('File Downloader')
self.setFixedSize(300, 100)
self.url_label = QLabel('URL:')
self.url_input = QLineEdit(self)
self.progress_bar = QProgressBar(self)
self.progress_bar.setVisible(False)
self.download_button = QPushButton('Download', self)
layout = QVBoxLayout(self)
layout.addWidget(self.url_label)
layout.addWidget(self.url_input)
layout.addWidget(self.download_button)
layout.addWidget(self.progress_bar)
self.download_button.clicked.connect(self.start_download)
def start_download(self):
url = self.url_input.text()
if url:
self.progress_bar.setVisible(True)
self.progress_bar.setValue(0)
self.download_button.setEnabled(False)
self.manager = QNetworkAccessManager()
self.manager.finished.connect(self.download_finished)
self.manager.downloadProgress.connect(self.download_progress)
request = QNetworkRequest(QUrl(url))
self.reply = self.manager.get(request)
def download_finished(self, reply):
if reply.error() == QNetworkReply.NoError:
filename = reply.url().fileName()
with open(filename, 'wb') as f:
f.write(reply.readAll())
self.progress_bar.setValue(100)
else:
print(reply.errorString())
self.download_button.setEnabled(True)
def download_progress(self, received, total):
if total > 0:
self.progress_bar.setValue(int(received / total * 100))
if __name__ == '__main__':
app = QApplication(sys.argv)
downloader = Downloader()
downloader.show()
sys.exit(app.exec_())
```
这段代码使用PyQt5库来实现了一个简单的GUI界面,用户可以在界面上输入要下载的文件的URL,然后点击“Download”按钮开始下载。下载进度会以进度条的形式显示。
在代码中,我们创建了一个QNetworkAccessManager对象来处理网络请求,并通过调用QNetworkAccessManager的download()方法来下载文件。我们还使用QNetworkReply对象来处理下载进度和结果。
阅读全文