Qt使用QNetworkAccessManager获取FTP文件函数

自闭症网瘾萝莉.ら 提交于 2020-08-05 17:17:12
void Mystack::getFtpImg(QString ftpFilePath, QString curFileName)
{
    QNetworkAccessManager* myNetworkManager = new QNetworkAccessManager(this);
    QNetworkRequest myNetworkRequest;
    QNetworkReply *myNetworkReply;
    QFile* downloadedFile = new QFile("./"+curFileName);
    downloadedFile->open(QIODevice::WriteOnly);
    QUrl url;
    url.setScheme("ftp");
    url.setUserName(config.getSet()->value("FTP_USER_NAME").toString());
    url.setPassword(config.getSet()->value("FTP_PASS_WORD").toString());
    url.setHost(config.getSet()->value("FTP_HOST").toString());
    url.setPort(config.getSet()->value("FTP_PORT").toInt());
    url.setPath(ftpFilePath);
    Mymethod::record("try to download file by:"+url.toString(),PRINT_INFO);
    myNetworkRequest.setUrl(url);
    myNetworkReply = myNetworkManager->get(myNetworkRequest);
    QObject::connect(myNetworkReply,&QNetworkReply::readyRead,[=]{
        downloadedFile->write(myNetworkReply->readAll());
    });
    QObject::connect(myNetworkManager,&QNetworkAccessManager::finished,[=]{
        if(NULL==myNetworkReply)
        {
            Mymethod::record(getCodeLocate()+"myNetworkReply is null.",PRINT_ERR);
            return;
        }
        if(myNetworkReply->error() == QNetworkReply::NoError)
        {
            downloadedFile->close();
            Mymethod::record("download file success:"+curFileName,PRINT_INFO);
        }
        else
        {
            Mymethod::record(getCodeLocate()+QString("download file:%1 failed,err:%2").arg(curFileName).arg(myNetworkReply->errorString()),PRINT_ERR);
            downloadedFile->close();
        }
        myNetworkReply->deleteLater();
        downloadedFile->deleteLater();
        QObject::disconnect(myNetworkManager,0,0,0);
        myNetworkManager->deleteLater();
    });
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!