如何使用 qt network 库模拟表单文件上传?

#include <QCoreApplication>
#include <QImage>

int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    // [1] 准备图像二进制数据
    QImage image = QImage(R"(Snipaste_2022-01-19_16-39-23.png)");
    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer, "PNG");  // writes image into ba in PNG format

    // [2] 添加请求主体数据
    QHttpMultiPart multiPart(QHttpMultiPart::FormDataType);
    QHttpPart imagePart;
    imagePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/png"));
    imagePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"upload\";filename=\"image.png\""));
    imagePart.setBody(ba);
    multiPart.append(imagePart);

    // [3] POST 请求
    QNetworkAccessManager handle;
    QNetworkRequest request;

    // [3][1] URL
    QUrl url;
    url.setUrl(R"(http://127.0.0.1:8080/upload)");

    // [3][2] Param
    QUrlQuery query;
    query.addQueryItem("deviceId", "001");
    query.addQueryItem("no", "sz");
    url.setQuery(query);

    request.setUrl(url);

    // [3][3] POST
    auto reply = handle.post(request, &multiPart);

    // [4] Result
    QObject::connect(reply, &QNetworkReply::finished, &a, [reply]() { qDebug() << reply->readAll(); });

    return a.exec();
}
posted @ 2022-12-08 10:01  學海無涯  阅读(83)  评论(0编辑  收藏  举报