QT网络编程之文件下载 QNetworkRequest QNetworkReply QNetworkAccessManager

void FileDownLoad::start()
{
    m_file = new QFile(m_filePath, this);//m_filePath下载地址
    if (!m_file->open(QIODevice::WriteOnly)) {
        emit result(false, tr("Write file error!\n") + m_file->errorString());
        return;
    }

    QUrl u(m_url);
    QNetworkRequest request(u);
    QNetworkReply *reply = m_accessManager.get(request);
    m_reply = reply;
    connect(reply, SIGNAL(finished()), this, SLOT(onReplyFinished()));//处理下载结果
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(updateDataReadProgress(qint64,qint64)));//更新下载进度
}


void FileDownLoad::onReplyFinished()
{
    QNetworkReply *reply = dynamic_cast (sender());
    if (!reply){
        emit result(false, "reply is null!");
        return;
    }

    if (reply->error() != QNetworkReply::NoError) {
        QString errInfo = QString("errorID:%1, errorString:%2").arg(reply->error()).arg(reply->errorString());
        emit result(false, errInfo);
        return;
    }

    QByteArray data = reply->readAll();

    if (!data.isEmpty()) {
        int writeBytes = m_file->write(data);
        m_file->flush();
        if (writeBytes != data.size()) {
            emit result(false, tr("Write file error\n") + m_file->errorString());
            return;
        }
    }

    // check filesize
    int contentLength = reply->header(QNetworkRequest::ContentLengthHeader).toInt();

    if (contentLength == 0 || m_file->size() == 0 || contentLength != m_file->size()) {
        emit result(false, tr("Network error! code 400"));
        return;
    }

    emit result(true, "");
}


 

你可能感兴趣的:(QT实战项目应用)