Qt HTTP post文件

用Qt与服务器进行文件交互,开始想的用ftp,由于文件不大,不超过2M,所以互联网的同事建议用HTTP post。下面把Qt post文件的方法记录一下。

bool CImpedianceReport::PostPicture(int report_id, QString fileName)
{
    //设置发送的数据
    bool bRet = false;
    QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    //
    QHttpPart utPart;
    utPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"record_rcc_id\"")));
    utPart.setBody(QByteArray::number(report_id));

    //
    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data; name=\"%1\"; filename=\"%2\"")
                                                                            .arg("file1").arg(QFileInfo(fileName).fileName())));
    QFile *file = new QFile(fileName);      //由于是异步,所以记得一定要new
    file->open(QIODevice::ReadOnly);
    imagePart.setBodyDevice(file);          //方便后续内存释放
    file->setParent(multiPart); // we cannot delete the file now, so delete it with the multiPart
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, "image/png");

    //
    multiPart->append(utPart);
    multiPart->append(imagePart);

    //设置头信息
    QNetworkRequest networkRequest;
    networkRequest.setUrl(QUrl("http://report.cgwzjs.com/index.php/Api/report/uploadfiles"));

    //发送请求
    QEventLoop loop;
    QNetworkAccessManager manager;
    QObject::connect(&manager, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));

    QNetworkReply *reply = manager.post(networkRequest, multiPart);
    multiPart->setParent(reply); // delete the multiPart with the reply
    loop.exec();

    QByteArray data = reply->readAll();
    qDebug() << QString(data);

    QNetworkReply::NetworkError error = reply->error();
    if(error == QNetworkReply::NoError)
    {
        //{"status":1,"msg":"上传成功","info":{"file_url":{"file1":"/Uploads/image/1/41.png"}}}
        Json::Value root;
        Json::Reader reader;
        if(reader.parse(data.data() ,root))
        {
            if(root["status"].asInt() == 1)
            {
                bRet = true;
            }
        }
    }
    else
    {
            qDebug() << "post file error:" << QString(data);
    }
    reply->deleteLater();
    return bRet;
}

你可能感兴趣的:(Qt)