Reputation: 3559
I am using QT to upload a file to a web server. The web server accepts files using the following request:
curl -X POST -H 'Content-Type:multipart/form-data'
-H 'Authorization: Token <token>'
-F 'file=@file_to_upload.txt'
https://some.web.site/api/v2/files/contents/
I am using roughly this QT calls to try to accomplish the same:
QHttpMultiPart multiPart(QHttpMultiPart::FormDataType);
QHttpPart filePart;
file.open(QIODevice::ReadOnly)
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data");
filePart.setBodyDevice(file);
multiPart.append(filePart);
QNetworkAccessManager mgr;
QNetworkRequest req(url);
req.setRawHeader("Authorization", ("Token <token>").data());
QNetworkReply * reply(mgr.put(req, &multiPart));
Right now this is what I get from the server:
File object is missing or invalid.
Can someone stop what the QT part is missing compared to the curl command? I would guess qt is missing some step that curl does behind the scenes. I would rather prefer a solution that does not involve me putting the whole request together manually.
Upvotes: 2
Views: 4224
Reputation: 4010
You should make some code modifications:
file.open(QIODevice::ReadOnly);
//add next lines
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/zip")); //or whatever type of your file.
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"file\""));
filePart.setHeader(QNetworkRequest::ContentLengthHeader, file.size());
//and your other code
filePart.setBodyDevice(file);
multiPart.append(filePart);
And also take attention that with curl
you make POST
request but with Qt
- put
. So also replace last line with this:
QNetworkReply * reply = mgr.post(req, &multiPart);
Upvotes: 3