Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Post request and file upload
Forum Update on Monday, May 27th 2025

Post request and file upload

Scheduled Pinned Locked Moved Solved General and Desktop
5 Posts 3 Posters 2.3k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Morgenstern
    wrote on last edited by
    #1

    Dear Developers,

    I am trying to upload a file on a server. The curl command looks like this:

    curl -X POST "https://my.labguru.com/api/v1/attachments?token=token" -H "accept: application/json" -H "Content-Type: multipart/form-data" -F "item[attachment]=file" -F "item[attach_to_uuid]=uuid" -F "item[title]=title"
    

    I already tried to use QNetworkAccessManager, which works well for post requests that don't require file upload. Here is the code I'm using :

    QNetworkRequest request;
        request.setHeader(QNetworkRequest::ContentTypeHeader, QByteArray("application/json"));
        request.setUrl(url);
    
        QJsonObject obj;
        QJsonObject item;
    
        obj["token"] = token;
        item["title"] = experimentLabguruName;
        item["project_id"] = IDProject;
        item["milestone_id"] = IDMilestone;
        obj["item"] = item;
    
        QJsonDocument doc(obj);
        QByteArray data = doc.toJson();
    
        QNetworkReply *reply = mgr->post(request, data);
    

    Unfortunately, it doesn't work if I use the same structure for the curl command previously described. I also tried to use QHttpMultiPart without success.

    I did not find anything explicit online but if you know the answer I'm all ears. Anyways, do you have any tips or any lead for me to solve this problem?

    Thanks in advance :D

    1 Reply Last reply
    1
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi and welcome to devnet,

      You should use a service that echos back the request you sent so you can compare what curl and QNetworkAccessManager are sending.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      2
      • Axel SpoerlA Offline
        Axel SpoerlA Offline
        Axel Spoerl
        Moderators
        wrote on last edited by Axel Spoerl
        #3

        Assuming that "doesn't work" means reply->readAll() returns an empty QByteArray:
        That's because the code doesn't wait for the server response to arrive.
        If you add...

        QEventLoop loop;
        QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
        loop.exec();
        qDebug() << reply->readAll();
        

        ...at the bottom of your code, it will debug the server's response (provided there is one).

        But that's blocking code, suitable for a prototype. The right thing to do is inheriting your class from QObject and connecting the finished signal of reply to a your own slot that processes the response.

        Software Engineer
        The Qt Company, Oslo

        1 Reply Last reply
        1
        • M Offline
          M Offline
          Morgenstern
          wrote on last edited by Morgenstern
          #4

          Hi,

          Sorry, I realize I were not explicit enough in my query.

          When I use the curl command, it gives <Response [201]> with the following headers :

          {
              "Cache-Control": "no-cache, no-store",
              "Connection": "Keep-Alive",
              "Content-Encoding": "gzip",
              "Content-Type": "application/json; charset=utf-8",
              "Date": "Mon, 01 Aug 2022 19:24:45 GMT",
              "ETag": "W/\"794e032167f22710d85e34ff09d659ed\"",
              "Expires": "Mon, 01 Jan 1990 00:00:00 GMT",
              "Keep-Alive": "timeout=15, max=100",
              "Pragma": "no-cache",
              "Referrer-Policy": "strict-origin-when-cross-origin",
              "Server": "nginx",
              "Status": "201 Created",
              "Strict-Transport-Security": "max-age=31536000; includeSubDomains, max-age=31536000; includeSubDomains",
              "Transfer-Encoding": "chunked",
              "Vary": "Accept-Encoding",
              "X-Content-Type-Options": "nosniff",
              "X-Download-Options": "noopen",
              "X-Frame-Options": "SAMEORIGIN",
              "X-Permitted-Cross-Domain-Policies": "none",
              "X-Powered-By": "Phusion Passenger 6.0.2",
              "X-Request-Id": "4ebf1405-4323-4417-9561-6b3cab611c0e",
              "X-Runtime": "1.151414",
              "X-XSS-Protection": "1; mode=block"
          }
          

          So everything works fine there.

          However, when I use the following code on Qt:

          QNetworkAccessManager *mgr = new QNetworkAccessManager(this);
              const QString token = tokenField->text();
              const QUrl url("https://cle.inserm.fr/api/v1/attachments?token=" + token);
          
              QNetworkRequest request;
              request.setHeader(QNetworkRequest::ContentTypeHeader, QByteArray("application/json"));
              request.setUrl(url);
          
              QHttpMultiPart *multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);
          
              QHttpPart filePart;
              filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"item[attachment]\""));
              QFile *file = new QFile(stfFile);
              file->open( QIODevice::ReadOnly);
              filePart.setBodyDevice(file);
          
              QHttpPart uuidPart;
              uuidPart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"item[attach_to_uuid]\""));
              uuidPart.setBody(QString("e7fa2cf3-9eba-478e-83a4-c2313e8878ae").toUtf8());
          
              QHttpPart titlePart;
              titlePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"item[title]\""));
              QString title = stfFile.split("/").last();
              titlePart.setBody(title.toUtf8());
          
              multiPart->append(filePart);
              multiPart->append(uuidPart);
              multiPart->append(titlePart);
          
              QNetworkReply *reply = mgr->post(request, multiPart);
              multiPart->setParent(reply);
          
              QObject::connect(reply, &QNetworkReply::finished, [reply, this](){
          
                  QString code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString();
              });
          

          It gives Error 400, Bad Request with the following headers:

          "Server nginx"
          "Content-Typeapplication/json; charset=utf-8"
          "Status 400 Bad Request"
          "Vary Accept-Encoding"
          "Content-Encoding gzip"
          "X-Request-Id 93bd4818-e7ed-469c-aef5-af3ab5b29ac0"
          "X-Runtime 0.170225"
          "X-Powered-By Phusion Passenger 6.0.2"
          "Connection close"
          "Transfer-Encodingchunked"
          

          I feel that I am not writing the Qt request correctly but I can't seem to understand what is wrong with the way I wrote it.

          Thanks for you help.

          1 Reply Last reply
          0
          • M Offline
            M Offline
            Morgenstern
            wrote on last edited by
            #5

            Problem solved :D

            I had to remove this line:

            request.setHeader(QNetworkRequest::ContentTypeHeader, QByteArray("application/json"));
            

            and for some reason to add a "filename" field in this line :

            filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"item[attachment]\"; "
                                                                                       "filename=\"" + title + "\""));
            
            1 Reply Last reply
            2

            • Login

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • Users
            • Groups
            • Search
            • Get Qt Extensions
            • Unsolved