QHttpMultipart doesn't send the file part
-
Hi, I'm trying to upload an image file to a django restful api, the thing is that django replies with this:
{ "image": [ "The submitted data was not a file. Check the encoding type on the form." ] }
I follow the Qt documentation to create my multipart request, this is the code:
void Client::initForFile(QString url) { responseStatus = false; request.setUrl(QUrl(url)); request.setHeader(request.ContentTypeHeader, "multipart/form-data"); } bool Client::post(QString url) { url.replace("file://", ""); file = new QFile(url); QFileInfo fileInfo(url); if(file->open(QIODevice::ReadOnly)) { multiPart = new QHttpMultiPart(QHttpMultiPart::FormDataType); multiPart->setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW"); QHttpPart filePart; filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"")); filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("form-data")); filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("image/"+fileInfo.suffix().toLatin1())); filePart.setBodyDevice(file); file->setParent(multiPart); multiPart->append(filePart); rawResponse = manager->post(request,multiPart); connect(rawResponse, &QNetworkReply::finished, this, &Client::responseRecieved); multiPart->setParent(rawResponse); return true; } qDebug()<<file->errorString(); return false; }
is there something I'm missing?. I tried to upload the same image using Postman an it works.
-
@Antonio-Ortiz
i suggest you compare the (raw) working request with the non-working request from Qt using Fiddler or Wireshark for example.
This should lead quickly to the cause -
@raven-worx said in QHttpMultipart doesn't send the file part:
request
Thanks for your quick reply, I'll try it
-
@Antonio-Ortiz said in QHttpMultipart doesn't send the file part:
filePart.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("form-data"));
filePart.setHeader(QNetworkRequest::ContentTypeHeader,
QVariant("image/"+fileInfo.suffix().toLatin1()));also you are overwriting the ContentType header here
-
Thanks for your answers, I found the problem, I forgot to set the filename to the file path in the header. I changed it to this:
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant("form-data; name=\"image\"; filename=\""+fileInfo.filePath()+"\""));
Thanks for the Wireshark advice @raven-worx, it was really helpful