下载函数
void downloadPackage(const StuFtpInfo& info,const QString& strLocalPath)
{
QUrl url;
url.setScheme("ftp");
url.setHost(info.strHost);
url.setPath(QString("/%1").arg(info.strFile));
url.setPort(21);
url.setPassword(info.strPwd);
url.setUserName(info.strUsr);
QNetworkRequest request;
request.setUrl(url);
m_pNetReply = m_pAccessManager->get(request);
m_replyTimer.setSingleShot(true);
m_replyTimer.setInterval(10 * 1000);
QEventLoop eventLoop;
connect(&m_replyTimer, &QTimer::timeout, [&] {
eventLoop.exit(-1);
});
if (m_pNetReply)
{
connect(m_pNetReply, static_cast<void(QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
[&](QNetworkReply::NetworkError code){
m_replyTimer.stop();
eventLoop.quit();
QMessageBox::information(this, "提示", QString("下载失败,错误码:%1.请重新下载!").arg(code));
});
connect(m_pNetReply, &QNetworkReply::finished, &eventLoop, &QEventLoop::quit);
}
m_replyTimer.start();
int nRet = eventLoop.exec();
if (nRet == -1)
{
eventLoop.quit();
QMessageBox::information(this, "提示", QString("下载请求超时"));
m_pNetReply->disconnect();
m_pNetReply->deleteLater();
}
}
请求成功读取文件数据
void slotReplyFinished(QNetworkReply* pReply)
{
m_replyTimer.stop();
QFile file(m_strLocalFileName);
if (!file.open(QIODevice::WriteOnly))
{
return;
}
file.write(pReply->readAll());
file.close();
pReply->deleteLater();
QFileInfo fInfo(m_strLocalFileName);
QString strDstDir = fInfo.path();
if (!uncompressZIP(m_strLocalFileName,strDstDir))
{
QMessageBox::information(this, "提示", QString("解压文件失败,请到目录下手动解压升级文件"));
}
ui.lineEditPackageName->setText(m_strLocalFileName);
QMessageBox::information(this, "提示", QString("下载成功"));
利用7za.exe解压文件
bool uncompressZIP(const QString& strZipFile, const QString& strDstDir)
{
QProcess process;
QString programPath = QCoreApplication::applicationDirPath();
QString strCmd = QString("7za.exe x -y %1 -o%2").arg(strZipFile).arg(strDstDir);
process.setWorkingDirectory(programPath);
process.start(strCmd);
return process.waitForFinished(10 * 1000);
}