Post request and file upload
-
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
-
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.
-
Assuming that "doesn't work" means
reply->readAll()
returns an emptyQByteArray
:
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 thefinished
signal ofreply
to a your own slot that processes the response. -
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.
-
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 + "\""));